在一些特定场景的业务需求下,日志需要写入到不同的路径下提供日志分析。
第一种:默认Nlog可以通过日志级别来区分路径,
——优点是不需要额外配置,开箱即用
——缺点是不够灵活,如果超过级别数量,则不满足需求
第二种:通过定义FileTarget来根据业务写入不同的地址
废话不多说了,直接上代码
1、创建NetCore,并且引入Nlog和NLog.Web.AspNetCore 这个就不介绍和贴图了
2、创建nlog配置文件
注意配置文件里面的:
<variable name="cuspath" value="" />
相当于根据变量的方式来定义日志输出目录
github文档说明地址:https://github.com/NLog/NLog/wiki/Configuration-file
在输入文件名称中加入变量名称:
fileName="logs/${var:cuspath}nlog-all-${shortdate}.log"
上面,默认是输出到logs/目录中
<?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方法里面注册下
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
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseNLog();
5、为了扩展,我们新建一个类来处理日志的写入
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 } }
注意:
public void Setting(string path)
方法是设置目录输入位置的
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,一群内心骚动的小青年