.net core日志结构化
前言
什么是结构化呢? 结构化,就是将原本没有规律的东西进行有规律话。
就比如我们学习数据结构,需要学习排序然后又要学习查询,说白了这就是一套,没有排序,谈如何查询是没有意义的,因为查询算法就是根据某种规律得到最佳的效果。
同样日志结构话,能够让我们得到一些好处。如果说容易检索,容易分析,总的来说就是让我们的日志更加有规律。
如果我们的日志结构化了,那么可以使用elasticsearch 这样的框架进行二次整理,再借助一些分析工具。
我们就能做到可视化分析系统的运行情况,做到日志告警、上下文关联、实现追踪系统集成,同样也易于检索相关信息。
说了这么多,其实对于程序员,就是为了节约排查错误的时间,然后在做系统稳定化方案的时候有依据,我们是讲道理的,做事要有依据,不能张口就来。
正文
这里结构化,借助需要借助serilog,引用serilog.aspnetcore。
开源地址如下:
这里介绍一下简单的接入方式:
在createhostbuilder 中加入useserilog:
public static ihostbuilder createhostbuilder(string[] args) => host.createdefaultbuilder(args) .configurewebhostdefaults(webbuilder => { webbuilder.usestartup<startup>(); }).useserilog(dispose:true);
然后在startup的configureservices的加入:
services.addlogserilog(configuration);
这个addlogserilog 是我写的扩展:
public static class serilogextension { public static serilog.ilogger addlogserilog(this iservicecollection services, iconfiguration configuration) { log.logger = new loggerconfiguration().readfrom.configuration(configuration) .minimumlevel.debug() .enrich.fromlogcontext() .writeto.console(new renderedcompactjsonformatter()) .writeto.file(formatter: new compactjsonformatter(), "logs\\test.txt", rollinginterval: rollinginterval.day) .createlogger(); return log.logger; } }
输出:
这时候发现我们的输出都json化了。
同时在根目录下的logs目录下输出日志文件:
但是我们这样发现,日志太多了,我们需要过滤掉一些日志,那么我们可以配置:
"serilog": { "minimumlevel": { "default": "information", "override": { "microsoft": "error", "system": "information" } } }
测试代码:
[httpget] public int getservice([fromservices]iselfservice selfservice) { _logger.loginformation("hello word"); return 1; }
结果:
因为上面配置了microsoft 为error级别的,故而系统打印的日志只有error基本才会输出。
这里面简单看一下serilog 的原理,
因为已经介绍了日志系统的基本结果,故而直接往下续:
查看useserilog:
public static ihostbuilder useserilog( this ihostbuilder builder, ilogger logger = null, bool dispose = false, loggerprovidercollection providers = null) { if (builder == null) throw new argumentnullexception(nameof (builder)); builder.configureservices((action<hostbuildercontext, iservicecollection>) ((_, collection) => { if (providers != null) servicecollectionserviceextensions.addsingleton<iloggerfactory>(collection, (func<iserviceprovider, m0>) (services => { serilogloggerfactory serilogloggerfactory = new serilogloggerfactory(logger, dispose, providers); foreach (iloggerprovider service in (ienumerable<iloggerprovider>) serviceproviderserviceextensions.getservices<iloggerprovider>(services)) serilogloggerfactory.addprovider(service); return (iloggerfactory) serilogloggerfactory; })); else servicecollectionserviceextensions.addsingleton<iloggerfactory>(collection, (func<iserviceprovider, m0>) (services => (iloggerfactory) new serilogloggerfactory(logger, dispose, (loggerprovidercollection) null))); seriloghostbuilderextensions.configureservices(collection, logger); })); return builder; }
这里我简单梳理一下日志系统的基本结构,首选是iloggerfactory, 里面会有一个createlogger,创建一个ilogger。那么这个ilogger的作用是什么呢?
是用来统一接口的。 比如说我们有文件日志,有控制台日志,有很多方式输出日志。那么就要有一个管理的来统一接口。
而每一种打印方式,继承iloggerprovider,比如consoleprovider继承iloggerprovider有一个createlogger方法,这个createlog才是创建具体的实现类,比如说consolelogger,consolelogger又继承ilogger。
从而ilogger的另一个实现类logger实现代理,管理其他继承ilogger的实现类。
可能我这样说有点模糊,那么请看完上面链接,应该就会明白我所以表达的意思。
那么回到上文中。
servicecollectionserviceextensions.addsingleton(collection, (func<iserviceprovider, m0>) (services => (iloggerfactory) new serilogloggerfactory(logger, dispose, (loggerprovidercollection)
将我们的iloggerfactory 替换成了serilogloggerfactory,官方是loggerfactory。
那么看下serilogloggerfactory:
public serilogloggerfactory( serilog.ilogger logger = null, bool dispose = false, loggerprovidercollection providercollection = null) { this._provider = new serilogloggerprovider(logger, dispose); this._providercollection = providercollection; } /// <summary>disposes the provider.</summary> public void dispose() { this._provider.dispose(); } /// <summary> /// creates a new <see cref="t:microsoft.extensions.logging.ilogger" /> instance. /// </summary> /// <param name="categoryname">the category name for messages produced by the logger.</param> /// <returns> /// the <see cref="t:microsoft.extensions.logging.ilogger" />. /// </returns> public microsoft.extensions.logging.ilogger createlogger(string categoryname) { return this._provider.createlogger(categoryname); } /// <summary> /// adds an <see cref="t:microsoft.extensions.logging.iloggerprovider" /> to the logging system. /// </summary> /// <param name="provider">the <see cref="t:microsoft.extensions.logging.iloggerprovider" />.</param> public void addprovider(iloggerprovider provider) { if (provider == null) throw new argumentnullexception(nameof (provider)); if (this._providercollection != null) this._providercollection.addprovider(provider); else selflog.writeline("ignoring added logger provider {0}", (object) provider, (object) null, (object) null); } }
那么继续查看createlogger,serilogloggerprovider的createlogger 及其相关:
private readonly serilog.ilogger _logger; public serilogloggerprovider(serilog.ilogger logger = null, bool dispose = false) { if (logger != null) this._logger = logger.forcontext((ienumerable<ilogeventenricher>) new serilogloggerprovider[1] { this }); if (!dispose) return; if (logger != null) this._dispose = (action) (() => { if (!(logger is idisposable disposable)) return; disposable.dispose(); }); else this._dispose = new action(log.closeandflush); } public microsoft.extensions.logging.ilogger createlogger(string name) { return (microsoft.extensions.logging.ilogger) new seriloglogger(this, this._logger, name); }
而seriloglogger 就是具体来管理全部继承ilogger具体的实现的类。 那么是否是和官方一样,其他实现类都是继承自ilogger的呢?答案不是,他们都继承自ilogeventsink,下面会继续提及,暂时不要关心这个。
同时要忘记官方每个实现具体打印的类继承ilogger,它的设计思想还是一样的,只是换了一个继承接口。
seriloglogger 里面继承microsoft.extensions.logging.ilogger,实现具体的打印的。
看下seriloglogger 的具体的部分,主要看log方法,因为这个实现打印的,这下面不用看太多,只需要看到其实里面是调用_logger的方法就行。
internal class seriloglogger : microsoft.extensions.logging.ilogger { private static readonly messagetemplateparser messagetemplateparser = new messagetemplateparser(); private static readonly logeventproperty[] loweventidvalues = enumerable.range(0, 48).select<int, logeventproperty>((func<int, logeventproperty>) (n => new logeventproperty("id", (logeventpropertyvalue) new scalarvalue((object) n)))).toarray<logeventproperty>(); private readonly serilogloggerprovider _provider; private readonly serilog.ilogger _logger; public seriloglogger(serilogloggerprovider provider, serilog.ilogger logger = null, string name = null) { serilogloggerprovider serilogloggerprovider = provider; if (serilogloggerprovider == null) throw new argumentnullexception(nameof (provider)); this._provider = serilogloggerprovider; this._logger = logger; serilog.ilogger logger1 = this._logger; if (logger1 == null) logger1 = serilog.log.logger.forcontext((ienumerable<ilogeventenricher>) new serilogloggerprovider[1] { provider }); this._logger = logger1; if (name == null) return; this._logger = this._logger.forcontext("sourcecontext", (object) name, false); } public bool isenabled(loglevel loglevel) { return this._logger.isenabled(levelconvert.toseriloglevel(loglevel)); } public idisposable beginscope<tstate>(tstate state) { return this._provider.beginscope<tstate>(state); } public void log<tstate>( loglevel loglevel, eventid eventid, tstate state, exception exception, func<tstate, exception, string> formatter) { logeventlevel seriloglevel = levelconvert.toseriloglevel(loglevel); if (!this._logger.isenabled(seriloglevel)) return; serilog.ilogger logger = this._logger; string str1 = (string) null; list<logeventproperty> logeventpropertylist = new list<logeventproperty>(); if (state is ienumerable<keyvaluepair<string, object>> keyvaluepairs) { foreach (keyvaluepair<string, object> keyvaluepair in keyvaluepairs) { if (keyvaluepair.key == "{originalformat}" && keyvaluepair.value is string str2) str1 = str2; else if (keyvaluepair.key.startswith("@")) { logeventproperty property; if (logger.bindproperty(keyvaluepair.key.substring(1), keyvaluepair.value, true, out property)) logeventpropertylist.add(property); } else { logeventproperty property; if (logger.bindproperty(keyvaluepair.key, keyvaluepair.value, false, out property)) logeventpropertylist.add(property); } } type type = state.gettype(); typeinfo typeinfo = type.gettypeinfo(); if (str1 == null && !typeinfo.isgenerictype) { str1 = "{" + type.name + ":l}"; logeventproperty property; if (logger.bindproperty(type.name, seriloglogger.asloggablevalue<tstate>(state, formatter), false, out property)) logeventpropertylist.add(property); } } if (str1 == null) { string propertyname = (string) null; if ((object) state != null) { propertyname = "state"; str1 = "{state:l}"; } else if (formatter != null) { propertyname = "message"; str1 = "{message:l}"; } logeventproperty property; if (propertyname != null && logger.bindproperty(propertyname, seriloglogger.asloggablevalue<tstate>(state, formatter), false, out property)) logeventpropertylist.add(property); } if (eventid.id != 0 || eventid.name != null) logeventpropertylist.add(seriloglogger.createeventidproperty(eventid)); messagetemplate messagetemplate = seriloglogger.messagetemplateparser.parse(str1 ?? ""); logevent logevent = new logevent(datetimeoffset.now, seriloglevel, exception, messagetemplate, (ienumerable<logeventproperty>) logeventpropertylist); logger.write(logevent); } }
那么seriloglogger 的_logger 到底是什么呢?我们可以看到其实这个_logger 是serilogloggerfactory到serilogloggerprovider到seriloglogger一层一层传进去的,最后调用forcontext生成,上面可以看到具体各个的实例化函数。
如果我们不传的话,那么会默认使用 serilog.log.logger,在seriloglogger的实例化函数中这样写道:
serilog.ilogger logger1 = this._logger; if (logger1 == null) logger1 = serilog.log.logger.forcontext((ienumerable<ilogeventenricher>) new serilogloggerprovider[1] { provider }); this._logger = logger1;
而在useserilog中logger参数的参数介绍中也写道: the serilog logger; if not supplied, the static will be used.
之所以重点谈论这个_logger 这个数据,是为了引出serilog.log.logger这个东西,是不是感觉特别眼熟?我们在startup的configureservices中写道:
services.addlogserilog(configuration);
addlogserilog 为:
public static serilog.ilogger addlogserilog(this iservicecollection services, iconfiguration configuration) { log.logger = new loggerconfiguration().readfrom.configuration(configuration) .minimumlevel.debug() .enrich.fromlogcontext() .writeto.console(new renderedcompactjsonformatter()) .writeto.file(formatter: new compactjsonformatter(), "logs\\test.txt", rollinginterval: rollinginterval.day) .createlogger(); return log.logger; }
这里我们就生成了具体打印实现类的管理类,是代理模式哈。大体就是各个不同的实现类继承ilogeventsink,然后safeaggregatesink也继承自ilogeventsink,safeaggregatesink里面有个属性readonly ilogeventsink[] _sinks,然后调用serilog的 logger
类调用write方法会调用safeaggregatesink的emit。
safeaggregatesink类如下,主要看下emit方法:
class safeaggregatesink : ilogeventsink { readonly ilogeventsink[] _sinks; public safeaggregatesink(ienumerable<ilogeventsink> sinks) { if (sinks == null) throw new argumentnullexception(nameof(sinks)); _sinks = sinks.toarray(); } public void emit(logevent logevent) { foreach (var sink in _sinks) { try { // 调用不同的log打印的实现类 如文件、控制台 等 sink.emit(logevent); } catch (exception ex) { selflog.writeline("caught exception while emitting to sink {0}: {1}", sink, ex); } } } }
具体就不细写了,里面都是一些格式匹配的,根据我们上面的分析,其实我们应该知道先看createlogger这个函数哈,然后去看console这个函数。如对格式化感兴趣可
以去看下哈,里面又套了一层代理模式的娃。
以上就是.net core日志结构化相关总结的详细内容,更多关于.net core日志结构化的资料请关注其它相关文章!
上一篇: 微信小程序调用地图选取位置后返回信息