本文介绍了NLog不创建日志文件,通过代码进行配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用NLog v4.6.8。
通过如下代码配置:
public class Logger { public static void ConfigureLogger() { var config = new NLog.Config.LoggingConfiguration(); // target where to log to string logFileName = @"log.txt"; string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = path + logFileName, KeepFileOpen = true, OpenFileCacheTimeout = 5 }; // delete the log file, if it exists. string fullFilePath = path + logFileName; if (File.Exists(fullFilePath)) { File.Delete(fullFilePath); } // rules for mapping loggers to targets // minimum and maximum log levels for logging targets config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logfile); // apply config NLog.LogManager.Configuration = config; } // create an instance of the logger for each class public static NLog.Logger getLogger() { return NLog.LogManager.GetCurrentClassLogger(); } // Flush and close down internal threads and timers. public static void flushLogger() { NLog.LogManager.Shutdown(); } }典型用法如下:
Logger.Info("Doing something");程序集的目录中没有日志文件。为什么会这样?
找到的一些故障排除建议表明,出现这种情况的常见原因是未将NLog的配置文件复制到输出目录。但是,项目或解决方案中没有配置文件。只有一个对所需DLL的引用。 推荐答案乍一看,您的代码看起来有效。当然,请确保您先调用Logger.ConfigureLogger。
我认为这是写权限错误。您可以尝试写入临时文件夹。您还可以启用内部日志(从代码)
// In case of a console application: NLog.Common.InternalLogger.LogToConsole = true; // otherwise to file: recommended to use the temp dir NLog.Common.InternalLogger.LogFile = "c:\temp\log-internal.txt"; // Also needed. Try info level or otherwise debug and trace to get more details NLog.Common.InternalLogger.LogLevel = LogLevel.Info;明确地说,不需要配置XML--这是可选的
更多推荐
NLog不创建日志文件,通过代码进行配置
发布评论