简体   繁体   English

如何在C#中使用NLog获取程序中的日志记录日期(时间戳)

[英]How to get the logging date (timestamp) in a program using NLog in C#

I would like to obtain the date(timestamp) of my logger in a program. 我想在程序中获取记录器的日期(时间戳)。 I configured my logger like this: 我这样配置记录器:

        var fileTarget = new FileTarget();
        string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string fullPath = Path.Combine(folder, "Log.txt");

        if (!File.Exists(fullPath))
        {
            File.Create(fullPath);
        }

        fileTarget.FileName = fullPath;
        config.AddTarget("file", fileTarget);

        var fileRule = new LoggingRule("*", LogLevel.Warn, fileTarget);
        config.LoggingRules.Add(fileRule);

        LogManager.Configuration = config;

In my program, I have the following: 在我的程序中,我具有以下内容:

class Program 
{
   static Logger log = LogManager.GetCurrentClassLogger();

   static void Main(string[] args)
   {
      log.Warn("Testing");
      //How can I check the logging time here?
   }
}

I can not figure out how to do it. 我不知道该怎么做。 Any help will be appreciated 任何帮助将不胜感激

I know you can have that in the log file created but I would like to obtain it directly in my program and use it. 我知道您可以在创建的日志文件中使用它,但是我想直接在我的程序中获取并使用它。

then the simplest solution would be to use DateTime.Now and log the value by hand inside the code: 那么最简单的解决方案是使用DateTime.Now并在代码中手动记录该值:

class Program 
{
   static Logger log = LogManager.GetCurrentClassLogger();

   static void Main(string[] args)
   {
      log.Warn(DateTime.Now.ToString("HH:mm:ss.fff MM.dd.yyyy") + " | " + "Testing");
      //How can I check the logging time here?
      // Or if you want to have it after the logger call save it afterwards
      DateTime timeStamp = DateTime.Now;
   }
}

You can get access to the timestamp of the log-event if you create the NLog.LogEventInfo yourself and pass it to the logger (instead of just the string-message) 如果您自己创建NLog.LogEventInfo并将其传递给记录器(而不只是字符串消息),则可以访问日志事件的时间戳。

The NLog.LogEventInfo have a property called LogEventInfo.TimeStamp NLog.LogEventInfo具有一个称为LogEventInfo.TimeStamp的属性

http://caraulean.com/2016/timestamp-accuracy-and-resolution-in-nlog/ http://caraulean.com/2016/timestamp-accuracy-and-resolution-in-nlog/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM