Serilog作为日志框架,是一个不错的选择,ASP.net Core提供了很多关于Serilog的NuGet包,可以让你把日志输出到文件、控制台、数据库等。对于入库的日志,NuGet包提供的操作比较有限,有的甚至无法自定义字段,所以使用起来就不是那么友好了。
所以我们需要对WriteTo进行扩展,写入我们自己的数据库表,自己的字段,采集我们需要的信息等等。
这里需要用到.Net的类扩展功能。看看WriteTo是什么类型。
public LoggerSinkConfiguration WriteTo {
get;
internal set;
}
下面我们就要对LoggerSinkConfiguration类进行扩展。WriteTo.MySQL、WriteTo.MSSqlServer都是这个原理。
首选定义一个用来具体实现写写数据库的类,需要实现ILogEventSink接口。
using System;
using Serilog.Core;
using Serilog.Events;
using System.Threading.Tasks;
namespace MY.Extentions
{
public class DBLogEvent : ILogEventSink
{
//imp是数据库操作的对象,自己实现就好了,就是执行sql
private IDBImp imp;
public DBLogEvent()
{
imp = DBHelper.GetInstance().GetDBImp();
}
//实现ILogEventSink的方法,异步执行写操作
public void Emit(LogEvent logEvent)
{
Task task = new Task(() =>
{
WriteLog(logEvent);
});
task.Start();
}
///
/// 写入数据库
///
/// 从这里读取时间戳和传入的日志信息
private void WriteLog(LogEvent logEvent)
{
//只接受Information级别的
if (logEvent.Level != LogEventLevel.Information)
return;
string st = logEvent.Timestamp.ToString("yyyy-MM-dd HH:mm:ss");
string sql = string.Format("insert into Logs(Identifer,Content,LogTime,Params) values('{0}','{1}','{2}','{3}')"
, "111111111", st, log, "{id:001,name:老万}");
imp.ExecSql(sql, null);
}
}
}
上面操作就是把一些信息,写入到Logs数据表,这个表是我们自己建立的。
然后我们写扩展类。
using System;
using Serilog;
using Serilog.Configuration;
using Serilog.Core;
namespace MY.Extentions
{
///
/// 日志WriteTo扩展,写入自己的数据库
///
public static class LoggerConfigurationDBExtensions
{
public static LoggerConfiguration ToDB(this LoggerSinkConfiguration configer)
{
//这里创建DBLogEvent对象,并返回
ILogEventSink val = new DBLogEvent();
return configer.Sink(val, Serilog.Events.LogEventLevel.Debug, null);
}
}
}
初始化时就可以这样用。
LoggerConfiguration configuration = new LoggerConfiguration()
.MinimumLevel.Debug()//最小的输出单位是Debug级别的
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)//将Microsoft前缀的日志的最小输出级别改成Information
.Enrich.FromLogContext()
.WriteTo.RollingFile("logs/{Date}.log", shared: true, restrictedToMinimumLevel: LogEventLevel.Debug,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}")
//这个就是我们扩展的方法了
.WriteTo.ToDB();
这样,只要你通过Serilog进行日志操作时,都会执行ToDB方法,写入信息到你自己的数据库。



