在多线程环境中使用NLog

时间:2017-08-01 22:15:30

标签: c# asp.net wpf multithreading nlog

我有一个WPF应用程序,它启动后台工作程序,即Asp.Net Core Web API服务器。

我想在一个日志文件中记录所有事件。 注意:我也希望从Microsoft登录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 个答案:

答案 0 :(得分:1)

咦! 愚蠢的错误,我没有设置&#34;复制到输出目录&#34;到&#34;永远复制&#34;在nlog.config文件中。