簡體   English   中英

NLog 不創建日志文件,通過代碼配置

[英]NLog not creating log files, configuration through code

使用 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 的配置文件沒有被復制到 output 目錄中。 但是,項目或解決方案中沒有配置文件。 只需要參考所需的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 配置 - 這是可選的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM