簡體   English   中英

這是使用 NLog 登錄到特定目標的正確方法嗎?

[英]Is this the correct way to log to a specific target with NLog?

我想將一些特殊事件記錄到一個不同的表中,該表將包含比一般應用程序日志更多的數據。

如果我向NLog.config添加第二個數據庫目標,我該如何在我的代碼中使用它?

這是正確的做法嗎:

NLog
    .LogManager
    .Configuration
    .AllTargets
    .Single(x => x.Name == "mySecondLogTable")
    .WriteAsyncLogEvent(...);

然后在NLog.config我會在規則元素中跳過這個目標,對嗎?


摘要: 我想定義多個數據庫目標,例如通用日志和專用日志,用於需要將更多詳細信息記錄到不同表中的情況。 我想在默認情況下使用通用日志,並且僅在由於其業務邏輯而需要這種特殊日志記錄的函數中使用特殊日志。

您始終可以創建另一個記錄器實例並使用 NLog LoggingRules 重定向到所需目標。

例如,我想將擴展日志記錄到一個單獨的文件中。 然后我去創建:

<nlog>
  <rules>
    <!--- Notice that final=true stops the logevents from also reaching defaultTarget -->
    <logger name="ExtendedLogging" minlevel="Trace" writeTo="extendedTarget" final="true" />
    <!--- Wildcard rule will capture all logevents not matching the "final" rule above -->
    <logger name="*" minlevel="Trace" writeTo="defaultTarget" />
  </rules>
    
  <targets>
    <target name="extendedTarget" xsi:type="File" fileName="ExtendedLog_${shortdate}.log" />
    <target name="defaultTarget" xsi:type="File" fileName="AppLog_${shortdate}.log" />
  </targets>
</nlog>

然后我去代碼並創建

private readonly Logger logger = LogManager.GetLogger("ExtendedLogging");

我認為在配置文件中搜索某些內容並通過后門之類的內容執行日志記錄並不是一個好主意。 最好將所有這些事情都明確說明。

另見: https : //github.com/nlog/nlog/wiki/Configuration-file#rules

    var fileLogger = LogManager.Configuration.AllTargets.Single(x => x.Name == "file");
    fileLogger.WriteAsyncLogEvents(
                            new LogEventInfo(LogLevel.Info, null, error.ToString())
                            .WithContinuation(new NLog.Common.AsyncContinuation(_ => { })));

我不確定我做了什么,但它有效。 因為接受的解決方案沒有

暫無
暫無

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

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