标签: nlog

NLog 在 Linux 上不起作用

我有在 Ubuntu 16.04 上运行的 asp.net core 1.1 应用程序。使用 NLog 配置日志记录:

    loggerFactory.AddNLog();
    loggerFactory.ConfigureNLog("nlog.config");
    app.AddNLogWeb();
Run Code Online (Sandbox Code Playgroud)

在我的开发 Windows 系统上,一切正常:已创建日志文件夹并且日志记录按预期工作。但是在 Linux 上日志记录不起作用。怎么了?

配置文件

<?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="internal-nlog.txt">
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <variable name="logDirectory" value="logs/${shortdate}" />
  <variable name="logRootDirectory" value="logs" />

  <targets>
    <target name="fileLogTrace" xsi:type="File" fileName="${logDirectory}/trace.txt" />
    <target name="fileLogDebug" xsi:type="File" fileName="${logDirectory}/debug.txt" />
    <target name="fileLogInfo" xsi:type="File" fileName="${logDirectory}/info.txt" />
    <target name="fileLogWarn" xsi:type="File" fileName="${logDirectory}/warn.txt" />
   </targets>

  <rules>
    <logger name="*" level="Trace" writeTo="fileLogTrace" />
    <logger name="*" level="Debug" writeTo="fileLogDebug" />
    <logger name="*" level="Info" writeTo="fileLogInfo" />
    <logger …
Run Code Online (Sandbox Code Playgroud)

c# linux nlog asp.net-core

1
推荐指数
1
解决办法
3249
查看次数

NLog 不写入事件日志 .NET Core 2.1

我已将 NLog 添加到我的 .NET 核心控制台应用程序中,它适用于文件和数据库目标。但是,当我尝试让它与 eventviewer 一起使用时,它不会记录任何内容。当我为事件查看器目标添加代码时,文件和数据库部分不记录任何内容。当我删除它时,日志记录再次开始工作。

我使用 Powershell 为应用程序添加了一个新的事件查看器源,所以这不是问题。应用程序不会崩溃或报告错误,它运行良好但在包含事件查看器时不会记录任何内容。

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  internalLogFile="c:\temp\console-example-internal.log"
  internalLogLevel="Info" >

<targets>    
  <target xsi:type="File" name="logfile" fileName="c:\temp\console-example.log"
        layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-e
        vent-properties}" />

<target xsi:type="Console" name="console"
        layout="[${longdate}][${machinename}][${level:uppercase=true}] ${message} ${exception}" />

<target xsi:type="EventLog" name="eventlog" source="testlogging" log="Application"
        layout="${message}${newline}${exception:format=ToString}" />

  <target xsi:type="Database" name="database" >
      <connectionString>Server=test; Database=test; User Id=sa; Password=password;</connectionString>
      <commandText>
          INSERT INTO dbo.Log (Application, Logged, Level, Message, Logger, CallSite, Exception ) 
          VALUES (@Application, @Logged, @Level, @Message, @Logger, @Callsite, @Exception);
      </commandText>
      <parameter name="@application" layout="TestLoggingApp" />
      <parameter name="@logged" layout="${date}" /> …
Run Code Online (Sandbox Code Playgroud)

c# logging nlog asp.net-core asp.net-core-2.1

1
推荐指数
1
解决办法
1720
查看次数

ILogger&lt;&gt; 不会导致 NLog 登录文件

我正在使用 NLog 并且我正在尝试使用来自 Microsoft.Extensions.Logging qssembly 的 ILogger<> 记录事件。根据文档,一切都是正确的,例如 nlog.config 和 Ilogger 注入等,但 ILogger 的方法根本不起作用。

这些是一些有效的代码,我可以在文件中看到结果:

using NLog;
Logger logger = LogManager.GetLogger("foo");
logger.Info("Program started");
Run Code Online (Sandbox Code Playgroud)

但我正在尝试这个(这不起作用):

using Microsoft.Extensions.Logging;
public class UserController : ControllerBase
{
  public UserController(ILogger<UserController> logger)
  {
      _logger = logger;
  }

  public async Task<User> Create()
  {
      _logger.LogInformation("Create Method's called");
  }
}
Run Code Online (Sandbox Code Playgroud)

这是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="info"
  internalLogFile="C:\temp\internal-nlog.log">
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <targets async="true">
    <target xsi:type="File" 
            name="LogFile" 
            fileName="${basedir}\temp\nlog-${shortdate}.log" 
            layout="${longdate} | ${uppercase:${level}} | ${message} |     ${exception:format=tostring} …
Run Code Online (Sandbox Code Playgroud)

.net c# nlog .net-core asp.net-core

1
推荐指数
1
解决办法
2560
查看次数

NLog 适用于 ASP.NET Core 应用程序,但不适用于 .NET Core xUnit 测试项目

我创建了一个 .NET Core 类库,它定义实用程序类接口并实现每个接口,例如通过 ADO.NET 访问数据库等。

每个实现类都使用 NLog。这在包含并引用 .NET Core 类库的 ASP.NET Core Web 应用程序中非常有效。

但是,当我尝试在 .NET Core xUnit Test 项目的上下文中实例化这些相同的实现类时,我得到

无法将“NLog.Logger”类型的对象转换为“Microsoft.Extensions.Logging.ILogger”类型

我搜索过类似的问题但没有找到。

在每个类中我都声明了一个私有只读变量:

private readonly ILogger<DatabasePersistenceAdoDotNet> _logger = null;
Run Code Online (Sandbox Code Playgroud)

我像这样实例化这个变量:

_logger = (ILogger<DatabasePersistenceAdoDotNet>)NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
Run Code Online (Sandbox Code Playgroud)

这在包含并引用 .NET Core 类库的 ASP.NET Core Web 应用程序中有效,但在我的 .NET Core xUnit Test 项目中却崩溃了。

我怀疑这与 ASP.NET 的依赖项注入在 .NET Core xUnit Test 项目中不可用有关,但我无法弄清楚如何使我的实用程序包在这两种情况下都能正常工作。

c# nlog .net-core asp.net-core

1
推荐指数
1
解决办法
1853
查看次数

为什么我不能使用 nlog 将跟踪记录写入文件?

我开始学习如何在 .net core web API 应用程序中配置 nlog。并阅读了一些教程,并尝试从github的官方教程中实现实现

1)创建nlog.confiqxml文件

<?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="Trace" 
  internalLogFile="D:/Projects/appstore2/AppStore/AppStore.DataAccessLayer/Logs/InnerLog.txt">

<extensions>
  <!--enable NLog.Web for ASP.NET Core-->
  <add assembly="NLog.Web.AspNetCore"/>
</extensions>

<variable name="PathToFile" value="D:/Projects/appstore2/AppStore/AppStore.DataAccessLayer/Logs"/>

<!-- define various log targets -->
<targets async="true">    
  <!-- write logs to file -->
  <target name="logfile" xsi:type="File" fileName="D:/Projects/appstore2/AppStore/AppStore.DataAccessLayer/Logs/${shortdate}_log.txt" layout="${longdate} ${level:uppercase=true} ${message}"/>

</targets>

<rules>
  <logger name="*" minlevel="Trace" writeTo="logfile" final="true"/>
</rules>
Run Code Online (Sandbox Code Playgroud)

2)配置我的Programm.cs

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

        try
        {
            logger.Debug("init main"); …
Run Code Online (Sandbox Code Playgroud)

c# logging nlog asp.net-web-api asp.net-core

1
推荐指数
1
解决办法
1789
查看次数

如何设置日志记录的当前时间(时区)?

我用于记录Microsoft.Extensions.Logging 和 NLog。日志写入Elasticsearch当我使用Kibana查找日志时,所有日志都是在 UT 写入的,这意味着与我的本地时间(时区)MET 相差两个小时。我想查看我的日志以及 Kibana 当地时间。如何调整日志记录的时区?

我添加 NLog.config:

<nlog autoReload="true" throwExceptions="false"
  internalLogLevel="Info" internalLogFile="NLogError.log"
  xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <targets>
 <target name="Logfile" xsi:type="File"
  fileName="${basedir}dap.log"
layout="${longdate} ${level} ${callsite} -> ${message} ${exception:format=Message,StackTrace}"
  archiveFileName="${basedir}/archives/log.{#}.log"
  archiveEvery="Day"
  archiveNumbering="Rolling"
  maxArchiveFiles="14"
  keepFileOpen="false"
  />

  <target xsi:type="Network"
        name="CentralLog"
        newLine ="false"
        maxMessageSize="65000"
        connectionCacheSize="5"
        encoding="utf-8"
        keepConnection="false"
        maxQueueSize="100"
        address="tcp://myurl.org:5544"
        onOverflow="Split">
  <layout type="JsonLayout">
    <attribute name="machinename" layout="${machinename}" />
    <attribute name="level" layout="${level:upperCase=true}" />
    <attribute name="processname" layout="${processname}" />
    <attribute name="processid" layout="${processid}" />
    <attribute name="sendertimestamp" layout="${date:universalTime=true:format=yyyy-MM-ddTHH\:mm\:ss.fff}" />
    <attribute name="module" layout="dhp DataPickerApi ${logger}" …
Run Code Online (Sandbox Code Playgroud)

logging timezone nlog elasticsearch

1
推荐指数
1
解决办法
3358
查看次数

在 appsettings.json 中为 NLog 连接字符串引用变量

appsettings.json我的项目中有这个文件,如下所示:

{
  "ConnectionStrings": {
    "MyConnectionString": "Server=SQLSERVER;Database=MyDatabse;Trusted_Connection=True;"
  },
  "NLog": {
    "targets": {
      "database": {
        "type": "Database",
        "dbProvider": "System.Data.SqlClient",
        "connectionString": "Server=SQLSERVER;Database=MyDatabse;Trusted_Connection=True;"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我不想在多个地方写我的连接字符串。我可以以某种方式引用以前的连接字符串吗?

我已经尝试过:"connectionString": "${appsetting:name=ConnectionStrings.MyConnectionString}",这是行不通的。

c# nlog appsettings .net-core asp.net-core

1
推荐指数
1
解决办法
926
查看次数

将nlog添加到.net core 3.0

将 nlog 添加到 .net core 3.0 应用程序会导致

“IServiceCollection”不包含“ConfigureLoggerService”的定义,并且找不到接受“IServiceCollection”类型的第一个参数的可访问扩展方法“ConfigureLoggerService”(您是否缺少 using 指令或程序集引用?)

对于 Nuget 我有

NLog.Extensions.Logging v1.6.1
NLog.Web.AspNetCore v4.9.0
Run Code Online (Sandbox Code Playgroud)

在启动.cs中

 public Startup(IConfiguration config)
        {
            LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
            Configuration = config;
        }

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
            services.AddMvc();
            services.AddTransient<ICwopaAgencyFileRepository, CwopaAgencyFileRepository>();
            services.AddTransient<ICurrentUserRepository, CurrentUserRepository>();
            services.AddTransient<IUserRepository, UserRepository>();
            services.AddTransient<IRevenueReceivedRepository, RevenueReceivedRepository>();
            services.AddTransient<ILesseeRepository, LesseeRepository>();
            services.AddTransient<ITractLesseeJunctionRepository, TractLesseeJunctionRepository>();
            services.AddTransient<IPadRepository, PadRepository>();
            services.AddTransient<IWellRepository, WellRepository>();
            services.AddTransient<IWellOperarationRepository, WellOperationRepository>();
            services.AddTransient<IRoyaltyRepository, RoyaltyRepository>();
            services.AddTransient<IRoyaltyAdjustmentCardViewModelRepository, RoyaltyAdjustmentCardViewModelRepository>();
            services.AddSingleton<ILoggerManager, LoggerService>();
            string conString = Configuration["ConnectionStrings:DefaultConnection"];
            services.AddDbContext<DataContext>(options =>
                options.UseSqlServer(conString));
            services.ConfigureLoggerService();
            services.AddMvc(option => option.EnableEndpointRouting = false);
            services.AddMemoryCache();
            services.AddSession();
        }
Run Code Online (Sandbox Code Playgroud)

这是我的 csproj 文件

<Project Sdk="Microsoft.NET.Sdk.Web"> …
Run Code Online (Sandbox Code Playgroud)

c# nlog nuget asp.net-core-mvc

1
推荐指数
1
解决办法
2125
查看次数

NLog:为什么 BufferingWrapper 似乎不缓冲日志条目

我有一个简单的 .Net core (2.2) 控制台应用程序。我正在尝试将其配置为与 NLog 一起使用。为简单起见,我使用“文件”目标。我正在尝试配置缓冲包装器,因此我将目标包装如下:

<target name="bufferWrapper" xsi:type="BufferingWrapper" bufferSize="100">
   <target name="logfile" xsi:type="File" fileName="file.txt" />
</target>
Run Code Online (Sandbox Code Playgroud)

当我在写入 Nlog 后立即在断点处停止调试模式时:

Logger.Info("Hello world");
Run Code Online (Sandbox Code Playgroud)

我看到日志条目已添加到“file.txt”中。我本以为它只有在累积 100 个日志条目后才将条目刷新到文件中(如bufferSize=100)。

谢谢你的帮助

c# nlog nlog-configuration .net-core

1
推荐指数
1
解决办法
886
查看次数

NLog 不会在进程退出时刷新所有日志条目

在此线程中 -当调用 Flush() 时,NLog 是否应该刷新 AsyncTargetWrapper 中的所有排队消息?- 我读到 \xe2\x80\x9eLogManager在域卸载或进程退出\xe2\x80\x9c 时将配置设置为 null(请参阅第一个答案中的编辑部分)。根据我的理解,这应该会导致所有待处理的日志条目被写入已注册的目标。然而,在FileTarget用wrapped with进行测试后AsyncTargetWrapper,这并不成立。我在 GitHub 上创建了一个最小的重现 - https://github.com/PaloMraz/NLogMultiProcessTargetsSample,其工作原理如下:

\n\n

LogLib是一个.netstandard2.0引用NLog4.6.8 NuGet 包并公开一个CompositeLogger以编程方式配置NLog目标的类的库:

\n\n
public class CompositeLogger\n{\n  private readonly ILogger _logger;\n\n  public CompositeLogger(string logFilePath)\n  {\n    var fileTarget = new FileTarget("file")\n    {\n      FileName = logFilePath,\n      AutoFlush = true\n    };\n    var asyncTargetWrapper = new AsyncTargetWrapper("async", fileTarget)\n    {\n      OverflowAction = AsyncTargetWrapperOverflowAction.Discard\n    };\n\n    var config = new LoggingConfiguration();\n    config.AddTarget(asyncTargetWrapper);\n …
Run Code Online (Sandbox Code Playgroud)

.net c# logging nlog multiprocessing

1
推荐指数
1
解决办法
3569
查看次数