2017-08-01 225 views
0

我有一個WPF應用程序,它啓動後臺工作者,即Asp.Net Core Web API服務器。在多線程環境中使用NLog

我想在一個日誌文件中記錄所有事件。 注:我希望ASP.net核心框架從微軟登錄。 我爲此使用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="true" 
     internalLogLevel="Warn" 
     internalLogFile="c:\temp\internal.txt"> 


    <!-- define various log targets --> 
    <targets> 
    <!-- write logs to file --> 
    <target xsi:type="File" name="allfile" fileName="c:\temp\TestSimLogs\nlog-all-${shortdate}.log" 
       layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" concurrentWrites="true" keepFileOpen="true"/> 

    <target xsi:type="File" name="ownFile" fileName="c:\temp\TestSimLogs\nlog-own-${shortdate}.log" 
       layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" concurrentWrites="true" keepFileOpen="true"/> 

    <target xsi:type="Null" name="blackhole" /> 
    </targets> 

    <rules> 
    <!--All logs, including from Microsoft--> 
    <logger name="*" minlevel="Trace" writeTo="allfile" /> 
    </rules> 
</nlog> 

在WPFfile.cs:

參考文獻:NLOG

private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); 

//lots of code 

private void Button_StartServer(object sender, RoutedEventArgs e) 
     { 
      Logger.Info($"Started Server in mode {mode}"); 

      // logic 
      WebSocket_Worker.RunWorkerAsync("WS begin"); 
      WebAPI_Worker.RunWorkerAsync("WebAPI begin"); 

      Status = $"Server Started in mode {mode}"; 
     } 

在Asp.Net核心:

參考文獻:Nlog.Extensions.Logging,Nlog.Web.AspNetCore

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
     { 
      loggerFactory.AddNLog(); 
      app.AddNLogWeb(); 
      env.ConfigureNLog("./../../nlog.config");  
      app.UseMiddleware_Authorization(); 
      app.UseMvc(); 
     } 

問題: 日誌文件不符合預期。日誌文件中只顯示asp.net核心日誌。

回答

1

唉! 愚蠢的錯誤,我沒有設置「複製到輸出目錄」到nlog.config文件中的「始終複製」。