我正在使用 Nlog 来编写日志文件。除非我们使用 Microsoft Excel 打开日志文件,否则它运行良好。但是,如果我使用记事本/记事本++ 打开它可以正常工作。即使文件是用 Excel 打开的,也可以记录消息。
这是我的 NLog 配置代码。
public class NLogLogger
{
public static Logger Instance { get; private set; }
public NLogLogger()
{
// Step 1. Create configuration object
LoggingConfiguration config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
FileTarget fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
// Step 3. Set target properties
CsvLayout csvLayout = new CsvLayout();
CsvColumn dateColumn = new CsvColumn() { Name = "Time", Layout = @"${date:format=dd.MM.yyyy HH\:mm\:ss}" };
csvLayout.Columns.Add(dateColumn);
CsvColumn levelColumn = new CsvColumn() { Name = "Level", Layout = @"${level:uppercase=true}" };
csvLayout.Columns.Add(levelColumn);
CsvColumn loggerColumn = new CsvColumn() { Name = "Logger", Layout = @"${logger}" };
csvLayout.Columns.Add(loggerColumn);
CsvColumn messageColumn = new CsvColumn() { Name = "Message", Layout = @"${message}" };
csvLayout.Columns.Add(messageColumn);
CsvColumn exceptionColumn = new CsvColumn() { Name = "Exception", Layout = @"${exception:format=ToString}" };
csvLayout.Columns.Add(exceptionColumn);
fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
fileTarget.ArchiveEvery = FileArchivePeriod.Day;
fileTarget.FileName = "${basedir}/file.csv";
fileTarget.Layout = csvLayout;
// Step 4. Define rules
LoggingRule rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
config.LoggingRules.Add(rule);
// Step 5. Activate the configuration
LogManager.Configuration = config;
InternalLogger.LogFile = @"c:\temp\LoggerErrors.txt";
// set internal log level
InternalLogger.LogLevel = LogLevel.Trace;
// Example usage
Instance = LogManager.GetLogger("NLogLogger");
}
public void LogError(Exception exception, string message = "")
{
Instance.ErrorException(message, exception);
}
}