ilogger简单使用
asp.net core
的webapplicationbuilder
中自带了一个日志组件。无需手动注册服务就能直接在控制器中构造注入。
public homecontroller(ilogger<homecontroller> logger) { _logger = logger; }
_logger.logtrace("trace{path}", httpcontext.request.path); _logger.logdebug("debug{path}", httpcontext.request.path); _logger.loginformation("info{path}", httpcontext.request.path); _logger.logwarning("warn{path}", httpcontext.request.path); _logger.logerror("error{path}", httpcontext.request.path); _logger.logcritical("critical{path}", httpcontext.request.path); _logger.log(loglevel.information, "log{path}", httpcontext.request.path);
打印效果如下
在一个日志输出中,日志的第一行输出是日志类别,来自泛型参数<homecontroller>的完全限定类名。第二行是模板字符串输出,可以看到从info级别开始才有输出,这是因为在appsetting文件中配置了loglevel为information,过滤掉了该等级之下的输出。
msdn推荐在方法中多次详细的打印日志,但打印方法使用trace或information。开发时将日志等级设置为warn,避免过多信息显示。在排查故障时才将日志等级设置为trace
打印异常信息
try { throw new exception("自定义异常"); } catch (exception e) { _logger.logtrace("trace{path}", e); _logger.logdebug("debug{path}", e); _logger.loginformation("info{path}", e); _logger.logwarning("warn{path}", e); _logger.logerror("error{path}", e); _logger.logcritical("critical{path}", e); _logger.log(loglevel.information, "log{path}", e.tostring()); }
打印效果如下
日志的第一行是泛型参数,第二行开始是字符串模板。其中有参数e的异常类型,异常信息e.message
。第三行开始时异常的调用堆栈e.stacktrace
最后一个打印中调用了e.tostring()
,结果是一样的。由此可见日志打印时,碰到了非字符串参数,就会调用其tostring()方法。那么我们可以通过重写这个方法来改变日志输出吗?
重写tostring
public class person { public int id { get; set; } public string name { get; set; } public int age { get; set; } public override string tostring() { return jsonserializer.serialize(this); } } _logger.logerror("{path}", new person() { id=1,name="张三",age=19}); _logger.logcritical("{path}", new person() { id = 2, name = "王浩", age = 20 });
这里我在重写中调用了序列化方法,打印结果是一个json数据
日志配置方式
配置日志文件介质,有三种方法,都是iloggingbilder
调用addconsole
。他们差不多,但有微小差别。第一种是配置容器中的日志服务,后面两种是配置服务主机上的日志。
主机生成器会初始化默认配置,然后在生成主机时将已配置的 iloggerfactory 对象添加到主机的 di 容器
所以效果是一样的
//第一种,配置应用程序级别的日志记录器 builder.services.addlogging(configure => { configure.addconsole(); }); //第二种,配置应用程序主机级别的日志记录器。和第三种一样,但不推荐使用这个。 builder.host.configurelogging(configure => { configure.addconsole(); }); //第三种,配置应用程序主机级别的日志记录器 builder.logging.addconsole();
log等级
在asp.net core的日志默认扩展中,定义logtrace
logdebug
loginformation
logwarning
logerror
logcritical
log
7种常用方法。对应的日志有7个级别
// 定义日志严重性级别。 public enum loglevel { //包含最详细消息的日志。这些消息可能包含敏感的应用程序数据 //默认情况下禁用这些消息,生产环境中永远不应启用 trace = 0, //用于开发过程中的交互式调查。这些日志主要包含调试有用的信息,没有长期价值 debug = 1, //跟踪应用程序的一般流程。这些日志应具有长期价值 information = 2, //强调应用程序流程中的异常或意外事件,但不会导致应用程序执行停止 warning = 3, //强调由于失败导致当前执行流程停止的日志。这些日志应指示当前活动中的失败,而不是应用程序范围的失败 error = 4, //描述不可恢复的应用程序或系统崩溃,或者需要立即关注的灾难性失败 critical = 5, //不用于编写日志消息。指定日志类别不应写入任何消息 none = 6, }
异常
在开发环境,builder默认会为应用配置这个异常中间件app.usedeveloperexceptionpage()
,这个配置是写在源码中的,所以不需要我们显式配置。如果我们不想显示这个页面,那可以配置中间件useexceptionhandler
。这个中间件要配置在usedeveloperexceptionpage后面,因为中间件调用是递归的,异常发生在终结点中间件中,之后就是请求处理管道递归跳出阶段,所以异常捕获也在这个阶段。调用顺序和配置顺序是相反的。
或者根据环境app.environment.isdevelopment()
来判断使用是否使用useexceptionhandler。至于usedeveloperexceptionpage则不用担心,只要不是显示配置,开发环境中不会进入这个中间件。不知道是由于条件编译,还是做了环境判断。
还还有一种方法是在这两个中间件后面自定义中间件捕获异常,短路管道。
我注意到,不管使用usedeveloperexceptionpage还是useexceptionhandler中间件,控制台中都会出现异常日志,这是为什么?这是因为这两个中间件中都调用了日志打印。所以我们可以自己实现一个异常处理中间件,这样就不会打印日志了。
app.usedeveloperexceptionpage(); app.useexceptionhandler("/home/error"); app.use(async (context, next) => { try { await next(context); } catch (exception e) { await context.response.writeasync("custom exception middleware"); } });
碰到异常打印日志是正常操作,所以这不需要我们去关心。但是,在前面的截图中,useexceptionhandler中间件的异常打印的问题在于,没有打印请求路径、请求参数等信息。我们只知道哪里出错了,却不知道是什么原因引起的,怎么复现,这是很不完善的。不知道当初为什么这样设计。所以最好是自己重新写个异常处理中间件,设置响应内容以及控制日志打印。
自定义异常中间件打印请求和异常日志
public class exceptionmiddleware { private readonly requestdelegate next; public exceptionmiddleware(requestdelegate next) { this.next = next; } public async task invokeasync(httpcontext context) { try { await next(context); } catch (exception e) { var _logger=context.requestservices.getservice<ilogger<exceptionmiddleware>>(); var bodystring=""; if (context.request.contenttype==null || !context.request.contenttype.contains("multipart/form-data")) { using (streamreader reader = new streamreader(context.request.body, encoding.utf8)) { bodystring = await reader.readtoendasync(); } } else { //不包含文件实际内容 foreach (var formfield in context.request.form) { bodystring += formfield.key + " " + formfield.value+","; } } _logger.logerror("堆栈:{e}\n\t路径:{c}\n\t查询字符串:{p}\n\t内容:{f}", e,context.request.path,context.request.querystring,bodystring); await context.response.writeasync("custom exception middleware"); } } }
使用serilog输出日志到文件介质
由于asp.net core自己没有提供文件介质的提供程序,所以我转到使用serilog
。仅仅注册了一个服务,其他的一切不变。
引入包serilog.aspnetcore
。并不需要引入serilog.sinks.file
,因为serilog.aspnetcore已经引入了文件介质的提供程序
日志管线配置serilog提供程序
日志系统包括如下几个概念:日志管线、提供程序、介质。严格来说介质不算。
日志系统又叫日志管线logging pipeline
。日志管线中的每个提供程序都会处理一次日志,并输出到自己的介质中。
- 配置serilog子管线
log.logger = new loggerconfiguration() //最小输出等级 .minimumlevel.warning() //增加介质 .writeto.console() .writeto.file("logs/log-.txt", rollinginterval: rollinginterval.day) .createlogger(); //注册serilog服务 builder.services.addserilog();
- 配置完整的日志管线这里默认的控制台介质得到了两个提供程序,一个是默认的addconsole,一个是serilog的writeto.console。按照管线中配置的顺序,这两个提供程序都会向控制台打印一次。而serilog还向管线中添加了一个到文件介质的提供程序,所以还会产生一个日志文件。
builder.services.addlogging(logbuilder => { logbuilder //删除管线上默认的提供程序 .clearproviders() //serilog子管线上的提供程序合并进来 .addserilog() .addconsole(); });
- 控制台介质两个提供程序均处理了日志打印
- 文件介质
输出模板
回想默认日志提供程序和serilog日志提供程序,都会在我们的消息之外附加信息,比如等级、类名。这是怎么配置的?
- 默认日志提供程序的格式是
[loglevel]: [eventid] [category] message
。可以通过继承consoleformatter
改写模板。但是很麻烦。而且颜色,字体还不知道怎么控制。
public class customconsoleformatter : consoleformatter { private readonly string _formattemplate; public customconsoleformatter(ioptions<templatedconsoleformatteroptions> options) : base(name: "custom") { _formattemplate = options.value.template ?? "[{timestamp:hh:mm:ss} {level}] [{eventid}] {message}{newline}{exception}"; } public override void write<tstate>(in logentry<tstate> logentry, iexternalscopeprovider scopeprovider, textwriter textwriter) { var timestamp = datetime.utcnow; var level = logentry.loglevel.tostring(); var eventid = logentry.eventid.id; var message = logentry.formatter(logentry.state, logentry.exception); var exception = logentry.exception != null ? logentry.exception.tostring() : ""; var newline = environment.newline; var logoutput = replacetemplatevalues(_formattemplate, timestamp, level, eventid, message, exception, newline); textwriter.write(logoutput); } private string replacetemplatevalues(string template, datetime timestamp, string level, int eventid, string message, string exception, string newline) { return regex.replace(template, @"{(\w+)(?::([^}]+))?}", match => { var key = match.groups[1].value; var format = match.groups[2].value; switch (key) { case "timestamp": return timestamp.tostring(format); case "level": return level; case "eventid": return eventid.tostring(); case "message": return message; case "newline": return newline; case "exception": return exception; default: return match.value; } }); } } public class templatedconsoleformatteroptions : consoleformatteroptions { public string? template { get; set; } } //使用模板 builder.services.addlogging(logbuilder => { logbuilder .clearproviders() //.addserilog() .addconsole(option => { //使用名为custom的模板配置 option.formattername = "custom"; }) //添加一个控制台模板配置 .addconsoleformatter<customconsoleformatter, templatedconsoleformatteroptions>(foption => { foption.template = "[{timestamp:hh:mm:ss} {level}] [{eventid}] {message:lj}{newline}{exception}"; }); });
- serilog输出模板相比之下serilog就简单得多,直接指定模板就行
log.logger = new loggerconfiguration() //最小输出等级 .minimumlevel.warning() //增加介质 .writeto.console(outputtemplate: "{timestamp:yyyy-mm-dd hh:mm:ss.fff zzz} [{level:u3}] {message:lj}{newline}{exception}") .writeto.file("logs/log-.txt", rollinginterval: rollinginterval.day, outputtemplate: "{timestamp:yyyy-mm-dd hh:mm:ss.fff zzz} [{level:u3}] {message:lj}{newline}{exception}") .createlogger();
serilog还能向模板中增加字段,使用enrichers
log.logger = new loggerconfiguraition() .enrich.fromlogcontext() .enrich.withproperty("application", "demo") .writeto.file("logs/log-.txt", rollinginterval: rollinginterval.day, outputtemplate: "{timestamp:yyyy-mm-dd hh:mm:ss.fff zzz} [{level:u3}] {message:lj}{properties:j}{newline}{exception}") // 设置 threadcontext 或 callcontext 的属性 threadcontext.properties["userid"] = 42; callcontext.logicalsetdata("username", "john doe"); log.information("user {userid} logged in as {username}", threadcontext.properties["userid"], callcontext.logicalgetdata("username"));
到此这篇关于net core日志与异常的文章就介绍到这了,更多相关netcore日志内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论