< targets > < target name = “ f1 ” xsi :type = “ File ” fileName = “ file1.txt ” /> < target name = “ f2 ” xsi :type = “ File ” fileName = “ file2.txt ” /> < target name = “ n1 ” xsi :type = “ Network ” address = “ tcp:// localhost:4001 ” /> < target name = “ ds ” xsi :type = “ OutputDebugString ” /> </ targets >
NLog提供了许多预定义的目标。实际上创建自己的目标非常容易 - 请参阅如何编写自定义目标。
三、NLog使用:
在这里,我封装了一个NLog使用帮助类,提供给全站调用,这样就可以避免在不同的类中实例化Nlog对象的步骤。
LoggerHelper.cs:
/// <summary> /// nLog使用帮助类 /// </summary> public class LoggerHelper { /// <summary> /// 实例化nLog,即为获取配置文件相关信息 /// </summary> private readonly NLog.Logger _logger = LogManager.GetCurrentClassLogger(); private static LoggerHelper _obj; public static LoggerHelper _ { get => _obj ?? (new LoggerHelper()); set => _obj = value; } #region Debug,调试 public void Debug(string msg) { _logger.Debug(msg); } public void Debug(string msg, Exception err) { _logger.Debug(err, msg); } #endregion #region Info,信息 public void Info(string msg) { _logger.Info(msg); } public void Info(string msg, Exception err) { _logger.Info(err, msg); } #endregion #region Warn,警告 public void Warn(string msg) { _logger.Warn(msg); } public void Warn(string msg, Exception err) { _logger.Warn(err, msg); } #endregion #region Trace,追踪 public void Trace(string msg) { _logger.Trace(msg); } public void Trace(string msg, Exception err) { _logger.Trace(err, msg); } #endregion #region Error,错误 public void Error(string msg) { _logger.Error(msg); } public void Error(string msg, Exception err) { _logger.Error(err, msg); } #endregion #region Fatal,致命错误 public void Fatal(string msg) { _logger.Fatal(msg); } public void Fatal(string msg, Exception err) { _logger.Fatal(err, msg); } #endregion }
四、运行记录结果:
因为我在NLog.config配置文件中配置的日志存储路径为:ProjectLogs/当前时间(yyyy-MM-dd)/
如下图所示: