NLog不创建日志文件,通过代码进行配置

编程入门 行业动态 更新时间:2024-10-28 20:28:33
本文介绍了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不创建日志文件,通过代码进行配置

本文发布于:2023-07-16 19:09:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1124922.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   文件   日志   NLog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!