当我们搭建系统或者api 程序时,遇见报错的信息,做一个日志记录;现在很多优秀的第三方框架都已经集成了日志记录功能,如果不依赖框架也可以自己手写一个日志层。
一般处理日志的方式有三种
【1】:保存在本地txt 文本
【2】:保存在数据库;入写入日志到DB数据库
【3】:保存到服务器;如Windows EventLog 事件查看器里面的日志
下面简单说一下这三种:
创建枚举
public enum LogTarget{/// <summary>/// 文件/// </summary>File,/// <summary>/// DB/// </summary>Database,/// <summary>/// 系统/// </summary>EventLog //系统}
创建Logger类
FileLogger(本地txt)、DBLogger(数据库写入)、EventLogger(系统日志)
三种日志实现的具体方式
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DataLogger
{public abstract class LogBase{protected readonly object lockObj = new object();public abstract void Log(string message);}public class FileLogger : LogBase{private string filePath = Path.Combine(Environment.CurrentDirectory, "fileLog.txt");//public string filePath = $@"D:\Syn_Log\IDGLog{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-FFF")}.txt";public override void Log(string message){lock (lockObj){using (StreamWriter streamWriter = new StreamWriter(filePath, true)) //new StreamWriter(filePath)){streamWriter.WriteLine(message);streamWriter.Close();}}}}public class EventLogger : LogBase{public override void Log(string message){lock (lockObj){EventLog m_EventLog = new EventLog("");m_EventLog.Source = "IDGEventLog";m_EventLog.WriteEntry(message);}}}public class DBLogger : LogBase{string connectionString = string.Empty;public override void Log(string message){lock (lockObj){//Code to log data to the database}}}
}
创建LogHelper
用来实现写入 FileLogger、DBLogger、EventLogger
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DataLogger
{public static class LogHelper{private static LogBase logger = null;public static void Log(LogTarget target, string message){switch (target){case LogTarget.File:logger = new FileLogger();logger.Log(message);break;case LogTarget.Database:logger = new DBLogger();logger.Log(message);break;case LogTarget.EventLog:logger = new EventLogger();logger.Log(message);break;default:return;}}}
}
以上已经搭建好日志层
下面调用LogHelper,就能实现日志记录
try
{ MyWrite(process, $"时间:{DateTime.Now.ToString("yyyy-MM-dd tt hh:mm:ss")},同步数据开始,请等几分钟…");
}
catch (Exception ex)
{ClearMemory();LogHelper.Log(LogTarget.File, $"接口{process}:时间:{DateTime.Now.ToString("yyyy--MM-dd HH:mm:ss:fff")},错误:{ex.Message}");
}
效果显示