簡體   English   中英

在控制台級別打印部分消息,但使用 NLog 將整個消息打印到文件

[英]Print part of the message at the console level, but the entire message to a file using NLog

將整個異常 object 打印到控制台使其變得混亂。 有沒有辦法將ex.Message打印到控制台,但將整個 object(堆棧)打印到文件,和/或使用DebugTrace時?

假設異常exBlah blah..at System.Number.StringToNumber(String... str...:line 269 The _log.Error below should print Failed to... Error: Blah blah to console, but Failed to... Error: Blah blah..at System.Number.StringToNumber(String... str...:line 269 to file 或當使用_log.Debug_log.Trace時。

catch (Exception ex)
 {
     _log.Error($"Failed to... Error: {ex}");
 }

我應該只寫一些自定義Console目標,如此處所示並以某種方式處理消息 arguments 還是有其他更簡單的方法?

您可以使用${exception}上的Format -選項來控制其 output:

  • format=Message to only output 異常消息
  • format=ToString到 output Exception-ToString()
  • 等等
<nlog throwConfigExceptions="true">
   <targets>
      <target xsi:type="console" name="logConsole" layout="${time}|${level}|${message} ${exception:format=ShortType,Message}" />
   </targets>
   <rules>
      <logger name="*" minLevel="Debug" writeTo="logConsole" />
   </rules>
</nlog>

如果你想在控制台中看到完整的異常細節,但只在LogLevel.Error上,那么你可以這樣做:

<nlog throwConfigExceptions="true">
   <variable name="ConsoleInfoLayout" value="${time}|${level}|${message} ${exception:format=ShortType,Message}" />
   <variable name="ConsoleErrorLayout" value="${time}|${level}|${logger}|${message} ${exception:format=ToString}" />
   <variable name="ConsoleDefaultLayout" value="${when:when=level<=LogLevel.Warn:inner=${ConsoleInfoLayout}:else=${ConsoleErrorLayout}}" />

   <targets>
      <target xsi:type="console" name="logConsole" layout="ConsoleDefaultLayout" />
   </targets>
   <rules>
      <logger name="*" minLevel="Debug" writeTo="logConsole" />
   </rules>
</nlog>

暫無
暫無

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

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