【问题标题】:Get log file from NLog configuration instead of hardcoding从 NLog 配置中获取日志文件,而不是硬编码
【发布时间】:2020-10-01 20:14:40
【问题描述】:

我有一个.NET Core 应用程序,其中配置了NLog。这是NLog.config的内容:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="false" internalLogLevel="Error" internalLogToConsole="true" internalLogIncludeTimestamp="true" keepVariablesOnReload="true">
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>
    <variable name="appId" value="" />
    <variable name="componentId" value="" />
    <variable name="file-target-path" value="" />
    <variable name="file-target-name" value="" />
    <targets>
        <target xsi:type="Console" name="console-target" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}Z ${uppercase:${level}} APP=${var:appId} COMP=${var:componentId} [${when:when='${threadname}'=='':inner=${threadid}:else=${threadname}}] ${message} - Logger=${logger},Level=${uppercase:${level}},ThreadId=${threadid},${onexception:,Exception\=&quot;${exception:format=tostring}&quot;}" />
        <target xsi:type="File" name="file-target"
                layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}Z ${uppercase:${level}} APP=${var:appId} COMP=${var:componentId} [${when:when='${threadname}'=='':inner=${threadid}:else=${threadname}}] ${message} - Logger=${logger},Level=${uppercase:${level}},ThreadId=${threadid},${onexception:,Exception\=&quot;${exception:format=tostring}&quot;}"
                fileName="${basedir}/${var:file-target-path}/${var:file-target-name}.log"
                archiveFileName="${basedir}/${var:file-target-path}/${var:file-target-name}.{###}.txt"
                archiveEvery="Day"
                archiveNumbering="DateAndSequence"
                archiveAboveSize="5242880"
                archiveDateFormat="yyyyMMdd"
                maxArchiveDays="31" />
    </targets>
    <rules>
        <logger name="*" minLevel="Trace" writeTo="console-target" />
        <logger name="*" minLevel="Trace" writeTo="file-target" />
    </rules>
</nlog>

我现在正在编写一个类来解析日志以获得正则表达式值\sApplication Running\s([\-]+?)\s。我目前在StreamReader 中硬编码了日志文件路径,如下所示:

Regex regex = new Regex(@"\sApplication Running\s([\-]+?)\s");

            using (StreamReader reader = new StreamReader(@"C:\path\to\my\log_file.log"))
            {
                ...
            }

我如何更新它,以便从日志记录配置中获取日志文件,而不是在我的班级中对其进行硬编码?

【问题讨论】:

  • 你想用正则表达式做什么?请详细说明示例
  • 稍微改写了我的问题。我不太担心正则表达式,因为我是日志文件位置的硬编码。

标签: c# .net .net-core nlog


【解决方案1】:

您可以从 LogManager.Configuration 中检索日志文件位置。

var nlogFileTarget = LogManager.Configuration.AllTargets.OfType<FileTarget>().First();
var dummyEventInfo = new LogEventInfo { TimeStamp = DateTime.UtcNow };
var logFilePath = nlogFileTarget.FileName.Render(dummyEventInfo);

【讨论】:

  • 好,我认为通过使用LogManager.Configuration.FindTargetLogEventInfo.CreateNullEvent,这个答案是现在最好的。
  • 到了那里,但使用它给了我fileName "C:\\Users\\Path\\To\\src\\My.Application\\bin\\Debug\\netcoreapp3.1\\/./Logs/My.Application.log" string 作为logFilePath 值,我需要它类似于C:\\Users\\Path\\To\\src\\My.Application\\bin\\Debug\\netcoreapp3.1\\Logs\\My.Application.log
【解决方案2】:

类似的解决方案:

<nlog>
    <variable name="file-target-path" value="" />
    <variable name="file-target-name" value="" />
    <variable name="file-target-filename" value="${basedir}/${var:file-target-path}/${var:file-target-name}.log"" />

    <targets>
        <target xsi:type="File" name="file-target" fileName="${file-target-filename}" />
    </targets>
    <rules>
        <logger name="*" minLevel="Trace" writeTo="file-target" />
    </rules>
</nlog>

然后你可以这样做:

var filetargetPath = NLog.LogManager.Configuration?.Variables["file-target-filename"]?.Render(LogEventInfo.CreateNullEvent());

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多