当前位置: 代码网 > it编程>编程语言>Asp.net > Serilog .NET 中的日志使用技巧(使用方法)

Serilog .NET 中的日志使用技巧(使用方法)

2024年07月02日 Asp.net 我要评论
.net 中的日志使用技巧serilogserilog 是 .net 社区中使用最广泛的日志框架,所以笔者使用一个小节单独讲解使用方法。示例项目在 demo2.console 中。创建一个控制台程序,

.net 中的日志使用技巧

serilog

serilog 是 .net 社区中使用最广泛的日志框架,所以笔者使用一个小节单独讲解使用方法。

示例项目在 demo2.console 中。

创建一个控制台程序,引入两个包:

serilog.sinks.console
serilog.sinks.file

除此之外,还有 serilog.sinks.elasticsearchserilog.sinks.rabbitmq 等。serilog 提供了用于将日志事件以各种格式写入存储的接收器。下面列出的许多接收器都是由更广泛的 serilog 社区开发和支持的;https://github.com/serilog/serilog/wiki/provided-sinks

可以直接使用代码配置 serilog:

private static serilog.ilogger getlogger()
	{
		const string logtemplate = "{sourcecontext} {scope} {timestamp:hh:mm} [{level}] {message:lj} {properties:j} {newline}{exception}";
		var logger = new loggerconfiguration()
			.enrich.withmachinename()
			.enrich.withthreadid()
			.enrich.fromlogcontext()
#if debug
			.minimumlevel.debug()
#else
		                .minimumlevel.information()
#endif
			.writeto.console(outputtemplate: logtemplate)
			.writeto.file("log.txt", rollinginterval: rollinginterval.day, outputtemplate: logtemplate)
			.createlogger();
		return logger;
	}

如果想从配置文件中加载,添加 serilog.settings.configuration:

private static serilog.ilogger getjsonlogger()
	{
		iconfiguration configuration = new configurationbuilder()
								 .setbasepath(appcontext.basedirectory)
								 .addjsonfile(path: "serilog.json", optional: true, reloadonchange: true)
								 .build();
		if (configuration == null)
		{
			throw new argumentnullexception($"未能找到 serilog.json 日志配置文件");
		}
		var logger = new loggerconfiguration()
			.readfrom.configuration(configuration)
			.createlogger();
		return logger;
	}

serilog.json 配置文件示例:

{
  "serilog": {
    "using": [ "serilog.sinks.console", "serilog.sinks.file" ],
    "minimumlevel": {
      "default": "debug"
    },
    "enrich": [ "fromlogcontext", "withmachinename", "withthreadid" ],
    "writeto": [
      {
        "name": "console",
        "args": {
          "outputtemplate": "{sourcecontext} {scope} {timestamp:hh:mm} [{level}] {message:lj} {properties:j} {newline}{exception}"
        }
      },
      {
        "name": "file",
        "args": {
          "path": "logs/log-.txt",
          "rollinginterval": "day",
          "outputtemplate": "{sourcecontext} {scope} {timestamp:hh:mm} [{level}] {message:lj} {properties:j} {newline}{exception}"
        }
      }
    ]
  }
}

依赖注入 serilog。

引入 serilog.extensions.logging 包。

private static microsoft.extensions.logging.ilogger injectlogger()
	{
		var logger = getjsonlogger();
		var ioc = new servicecollection();
		ioc.addlogging(builder => builder.addserilog(logger: logger, dispose: true));
		var loggerprovider = ioc.buildserviceprovider().getrequiredservice<iloggerprovider>();
		return loggerprovider.createlogger("program");
	}

最后,使用不同方式配置 serilog 日志,然后启动程序打印日志。

static void main()
	{
		var log1 = getlogger();
		log1.debug("溪源more、痴者工良");
		var log2 = getjsonlogger();
		log2.debug("溪源more、痴者工良");
		var log3 = injectlogger();
		log3.logdebug("溪源more、痴者工良");
	}
20:50 [debug] 溪源more、痴者工良 {"machinename": "win-kqduladm5la", "threadid": 1}
20:50 [debug] 溪源more、痴者工良 {"machinename": "win-kqduladm5la", "threadid": 1}
20:50 [debug] 溪源more、痴者工良 {"machinename": "win-kqduladm5la", "threadid": 1}

在 asp.net core 中使用日志

示例项目在 demo2.api 中。

新建一个 asp.net core api 新项目,引入 serilog.aspnetcore 包。

在 program 中添加代码注入 serilog 。

var builder = webapplication.createbuilder(args);
log.logger = new loggerconfiguration()
	.readfrom.configuration(builder.configuration)
	.createlogger();
builder.host.useserilog(log.logger);
//builder.host.useserilog();

将前面示例中的 serilog.json 文件内容复制到 appsettings.json 中。

启动程序后,尝试访问 api 接口,会打印示例如下的日志:

microsoft.aspnetcore.hosting.diagnostics  20:32 [information] request finished http/1.1 get http://localhost:5148/weatherforecast - - - 200 - application/json;+charset=utf-8 1029.4319ms {"elapsedmilliseconds": 1029.4319, "statuscode": 200, "contenttype": "application/json; charset=utf-8", "contentlength": null, "protocol": "http/1.1", "method": "get", "scheme": "http", "host": "localhost:5148", "pathbase": "", "path": "/weatherforecast", "querystring": "", "eventid": {"id": 2}, "requestid": "0hmoonqo5onku:00000003", "requestpath": "/weatherforecast", "connectionid": "0hmoonqo5onku"}

如果需要为请求上下文添加一些属性信息,可以添加一个中间件,示例如下:

app.useserilogrequestlogging(options =>
{
	options.enrichdiagnosticcontext = (diagnosticcontext, httpcontext) =>
	{
		diagnosticcontext.set("traceid", httpcontext.traceidentifier);
	};
});
 http get /weatherforecast responded 200 in 181.9992 ms {"traceid": "0hmsd1oug2dhg:00000003" ... ...

对请求上下文添加属性信息,比如当前请求的用户信息,在本次请求作用域中使用日志打印信息时,日志会包含这些上下文信息,这对于分析日志还有帮助,可以很容易分析日志中那些条目是同一个上下文。在微服务场景下,会使用 elasticsearch 等日志存储引擎查询分析日志,如果在日志中添加了相关的上下文属性,那么在分析日志时可以通过对应的属性查询出来,分析日志时可以帮助排除故障。

如果需要打印 http 的请求和响应日志,我们可以使用 asp.net core 自带的 httploggingmiddleware 中间件。

首先注入请求日志拦截服务。

builder.services.addhttplogging(logging =>
{
    logging.loggingfields = httploggingfields.all;
	// 避免打印大量的请求和响应内容,只打印 4kb
    logging.requestbodyloglimit = 4096;
    logging.responsebodyloglimit = 4096;
});

通过组合 httploggingfields 枚举,可以配置中间件打印 request、query、httpmethod、header、response 等信息。

可以将httplogging 中间件放在 swagger、static 之后,这样的话可以避免打印哪些用处不大的请求,只保留 api 请求相关的日志。

app.usehttplogging();

httploggingmiddleware 中的日志模式是以 information 级别打印的,在项目上线之后,如果每个请求都被打印信息的话,会降低系统性能,因此我们可以在配置文件中覆盖配置,避免打印普通的日志。

"microsoft.aspnetcore.httplogging.httploggingmiddleware": "information"

上下文属性和作用域

示例项目在 demo2.scopelog 中。

日志范围注意事项
microsoft.extensions.logging.abstractions 提供 beginscopeapi,可用于添加任意属性以记录特定代码区域内的事件。

解释其作用

api 有两种形式:

idisposable beginscope<tstate>(tstate state)
idisposable beginscope(this ilogger logger, string messageformat, params object[] args)

使用如下的模板:

{sourcecontext} {timestamp:hh:mm} [{level}] (threadid:{threadid}) {message}{newline}{exception} {scope}

使用示例:

    static void main()
    {
        var logger = getlogger();
        using (logger.beginscope("checking mail"))
        {
            // scope is "checking mail"
            logger.loginformation("opening smtp connection");
            using (logger.beginscope("downloading messages"))
            {
                // scope is "checking mail" -> "downloading messages"
                logger.logerror("connection interrupted");
            }
        }
    }

image-20231220212411976

而在 serilog 中,除了支持上述接口外,还通过 logcontext 提供了在日志中注入上下文属性的方法。其作用是添加属性之后,使得在其作用域之内打印日志时,日志会携带这些上下文属性信息。

        using (logcontext.pushproperty("test", 1))
        {
            // process request; all logged events will carry `requestid`
            log.information("{test} adding {item} to cart {cartid}", 1,1);
        }

嵌套复杂一些:

using (logcontext.pushproperty("a", 1))
{
    log.information("carries property a = 1");
    using (logcontext.pushproperty("a", 2))
    using (logcontext.pushproperty("b", 1))
    {
        log.information("carries a = 2 and b = 1");
    }
    log.information("carries property a = 1, again");
}

当需要设置大量属性时,下面的方式会比较麻烦;

using (logcontext.pushproperty("test1", 1))
using (logcontext.pushproperty("test2", 2))
{
}

例如在 asp.net core 中间件中,我们可以批量添加:

    public async task invokeasync(httpcontext context, requestdelegate next)
    {
        var enrichers = new list<ilogeventenricher>();
        if (!string.isnullorempty(correlationid))
        {
            enrichers.add(new propertyenricher(_options.enricherpropertynames.correlationid, correlationid));
        }
        using (logcontext.push(enrichers.toarray()))
        {
            await next(context);
        }
    }

在业务系统中,可以通过在中间件获取 token 中的用户信息,然后注入到日志上下文中,这样打印出来的日志,会携带用户信息。

非侵入式日志

非侵入式的日志有多种方法,比如 asp.net core 中间件管道,或者使用 aop 框架。

这里可以使用笔者开源的 czgl.aop 框架,nuget 中可以搜索到。

czgl.aop

示例项目在 demo2.aoplog 中。

有一个类型,我们需要在执行 sayhello 之前和之后打印日志,将参数和返回值记录下来。

    public class hello
    {
		public virtual string sayhello(string content)
		{
			var str = $"hello,{content}";
			return str;
		}
    }

编写统一的切入代码,这些代码将在函数被调用时执行。

before 会在被代理的方法执行前或被代理的属性调用时生效,你可以通过 aspectcontext 上下文,获取、修改传递的参数。

after 在方法执行后或属性调用时生效,你可以通过上下文获取、修改返回值。

public class logattribute : actionattribute
	{
		public override void before(aspectcontext context)
		{
			console.writeline($"{context.methodinfo.name} 函数被执行前");
			foreach (var item in context.methodvalues)
				console.writeline(item.tostring());
		}
		public override object after(aspectcontext context)
		{
			console.writeline($"{context.methodinfo.name} 函数被执行后");
			console.writeline(context.methodresult.tostring());
			return context.methodresult;
		}
	}

改造 hello 类,代码如下:

[interceptor]
	public class hello
	{
		[log]
		public virtual string sayhello(string content)
		{
			var str = $"hello,{content}";
			return str;
		}
	}

然后创建代理类型:

        static void main(string[] args)
        {
            hello hello = aopinterceptor.createproxyofclass<hello>();
            hello.sayhello("any one");
            console.read();
        }

启动程序,会输出:

sayhello 函数被执行前
any one
sayhello 函数被执行后
hello,any one

你完全不需要担心 aop 框架会给你的程序带来性能问题,因为 czgl.aop 框架采用 emit 编写,并且自带缓存,当一个类型被代理过,之后无需重复生成。

czgl.aop 可以通过 .net core 自带的依赖注入框架和 autofac 结合使用,自动代理 ci 容器中的服务。这样不需要 aopinterceptor.createproxyofclass 手动调用代理接口。

czgl.aop 代码是开源的,可以参考笔者另一篇博文:

到此这篇关于serilog.net 中的日志使用技巧的文章就介绍到这了,更多相关serilog.net 日志内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com