NetCore 使用Nlog自定义日志写入路径配置方式
在一些特定场景的业务需求下,日志需要写入到不同的路径下提供日志分析。
第一种:默认Nlog可以通过日志级别来区分路径,
——优点是不需要额外配置,开箱即用
——缺点是不够灵活,如果超过级别数量,则不满足需求
第二种:通过定义FileTarget来根据业务写入不同的地址
废话不多说了,直接上代码
1、创建NetCore,并且引入Nlog和NLog.Web.AspNetCore 这个就不介绍和贴图了
2、创建nlog配置文件
注意配置文件里面的:
1 | <variable name= "cuspath" value= "" /> |
相当于根据变量的方式来定义日志输出目录
github文档说明地址:https://github.com/NLog/NLog/wiki/Configuration-file
在输入文件名称中加入变量名称:
1 | fileName= "logs/${var:cuspath}nlog-all-${shortdate}.log" <br>上面,默认是输出到logs/目录中 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?xml version= "1.0" encoding= "utf-8" ?> <nlog xmlns= "http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" autoReload= "true" throwConfigExceptions= "true" internalLogLevel= "info" > <!-- enable asp.net core layout renderers --> <extensions> <add assembly= "NLog.Web.AspNetCore" /> </extensions> <variable name= "cuspath" value= "" /> <!-- the targets to write to --> <targets> <!-- write logs to file --> <target xsi:type= "File" name= "allfile" fileName= "logs/${var:cuspath}nlog-all-${shortdate}.log" layout= "${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" /> <!-- another file log, only own logs. Uses some ASP.NET core renderers --> <target xsi:type= "File" name= "ownFile-web" fileName= "logs/${var:cuspath}nlog-all-${shortdate}.log" layout= "${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" /> </targets> <!-- rules to map from logger name to target --> <rules> <!--All logs, including from Microsoft--> <logger name= "*" minlevel= "Trace" writeTo= "allfile" /> <!--Skip non-critical Microsoft logs and so log only own logs--> <logger name= "Microsoft.*" maxlevel= "Info" final= "true" /> <!-- BlackHole --> <logger name= "*" minlevel= "Trace" writeTo= "ownFile-web" /> </rules> </nlog> |
3、注册,在Starup.cs文件中
Configure方法里面注册下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } loggerFactory.AddNLog(); env.ConfigureNLog( "nlog.config" ); app.UseMvc(); } |
4、Program.cs
1 2 3 4 | public static IWebHostBuilder CreateWebHostBuilder( string [] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseNLog(); |
5、为了扩展,我们新建一个类来处理日志的写入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | namespace FytSoa.Common { /// <summary> /// 日志模块 /// </summary> public class Logger { NLog.Logger _logger; private Logger(NLog.Logger logger) { _logger = logger; } public Logger( string name) : this (LogManager.GetLogger(name)) { } /// <summary> /// 单例 /// </summary> public static Logger Default { get ; private set ; } static Logger() { Default = new Logger(LogManager.GetCurrentClassLogger()); } private static string _path = "" ; /// <summary> /// 自定义输出目录,初始化 /// </summary> public void Setting( string path) { if (_path != path) { _path = path; LogManager.Configuration.Variables[ "cuspath" ] = path+ "/" ; } } /// <summary> /// 自定义写日志路径 /// </summary> /// <param name="msg">消息</param> /// <param name="path">写入地址</param> /// <returns></returns> public void Process( string msg, string path= "" ) { _logger.Debug(msg); } #region Debug public void Debug( string msg, params object [] args) { _logger.Debug(msg, args); //LogManager.Shutdown(); } public void Debug( string msg, Exception err) { _logger.Debug(err, msg); //LogManager.Shutdown(); } #endregion #region Info public void Info( string msg, params object [] args) { _logger.Info(msg, args); //LogManager.Shutdown(); } public void Info( string msg, Exception err) { _logger.Info(err, msg); //LogManager.Shutdown(); } #endregion #region Warn public void Warn( string msg, params object [] args) { _logger.Warn(msg, args); //LogManager.Shutdown(); } public void Warn( string msg, Exception err) { _logger.Warn(err, msg); //LogManager.Shutdown(); } #endregion #region Trace public void Trace( string msg, params object [] args) { _logger.Trace(msg, args); //LogManager.Shutdown(); } public void Trace( string msg, Exception err) { _logger.Trace(err, msg); //LogManager.Shutdown(); } #endregion #region Error public void Error( string msg, params object [] args) { _logger.Error(msg, args); //LogManager.Shutdown(); } public void Error( string msg, Exception err) { _logger.Error(err, msg); //LogManager.Shutdown(); } #endregion #region Fatal public void Fatal( string msg, params object [] args) { _logger.Fatal(msg, args); //LogManager.Shutdown(); } public void Fatal( string msg, Exception err) { _logger.Fatal(err, msg); //LogManager.Shutdown(); } #endregion } } |
注意:
1 | public void Setting( string path)<br>方法是设置目录输入位置的 |
6、使用方法
默认输出到logs文件夹
- Logger.Default.Info("TestDefault"+i);
自定义输入到其他目录
- 设置输出目录:Logger.Default.Setting("task");
- 调用日志方法:Logger.Default.Setting("task_log");
task_log会输出到logs/task 文件夹
开源项目NetCore 2.2 https://github.com/feiyit/FytSoaCms page razor方式
NetCore3.1 https://github.com/feiyit/FytSoa3.1 前后端分离
关注我,和小伙伴们在NetCore的代码里一起骚起来
群号:1060012125,一群内心骚动的小青年
本文作者:Jason.裕哥
本文链接:https://www.cnblogs.com/fuyu-blog/p/11813669.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步