Giter Site home page Giter Site logo

nlog / nlog.extensions.logging Goto Github PK

View Code? Open in Web Editor NEW
385.0 22.0 153.0 1.63 MB

NLog as Logging Provider for Microsoft Extension Logging

Home Page: https://nlog-project.org

License: BSD 2-Clause "Simplified" License

C# 98.12% PowerShell 1.88%
netstandard nlog netcore net-core logging-library csharp dotnet logger logging

nlog.extensions.logging's Introduction

NLog

NLog.Extensions.Logging & NLog.Extensions.Hosting

NuGet Release

NuGet Release

Build status

NLog.Extensions.Logging

NLog.Extensions.Logging makes it possible to use NLog together with Microsoft ILogger-abstraction and Dependency Injection.

Notice the standard NLog NuGet package is enough for using NLog Logger with simple console application on the .NET Core platform. Just add NLog.config file to the project, and follow the tutorial for using GetCurrentClassLogger().

NLog.Extensions.Hosting

NLog.Extensions.Hosting only introduces UseNLog() as extension-method for the IHostBuilder.

Note if using ASP.NET Core then instead install NLog.Web.AspNetCore.

Getting Started Tutorials:

nlog.extensions.logging's People

Contributors

304notmodified avatar akunzai avatar andreigorlov avatar anellomancante avatar daanl avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar githubpang avatar jeffreymercado avatar jez9999 avatar mickelsonmichael avatar oruban avatar repo-ranger[bot] avatar rodionovdmitry avatar seblucas avatar sheepreaper avatar sirentek avatar snakefoot avatar tpodolak avatar whoiskevinrich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nlog.extensions.logging's Issues

Dotnet Core programatically set config does not seem to use archiving related settings on FileTarget

We are using Nlog in an MvcCore project and setting up the configuration programatically.

public void ConfigureLogger(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            var logFolder = app.ApplicationServices.GetService<IOptions<AppOptions>>().Value.LogFolder;

            loggerFactory.AddNLog();

            var config = new LoggingConfiguration();

            var consoleTarget = new ColoredConsoleTarget();

            var fileTarget = new FileTarget();
            fileTarget.FileName = $"{logFolder}/nlog-all-${{shortdate}}.log";
            fileTarget.KeepFileOpen = false;

            fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
            fileTarget.ArchiveDateFormat = "yyyy-MM-dd_HH_mm";
            fileTarget.ArchiveAboveSize = 100;
            fileTarget.ArchiveFileName = $"{logFolder}/archived/nlog-all-archived-${{#}}.log";

            config.AddTarget("console", consoleTarget);
            config.AddTarget("file", fileTarget);

            var layout = @"${uppercase:${level}}: ${longdate}|${logger}${newline}${message}${newline}${exception:format=ToString,StackTrace}";
            consoleTarget.Layout = layout;
            fileTarget.Layout = layout;

            var consoleRule = new LoggingRule("*", NLog.LogLevel.Trace, consoleTarget);
            var fileRule = new LoggingRule("*", NLog.LogLevel.Trace, fileTarget);

            config.LoggingRules.Add(consoleRule);
            config.LoggingRules.Add(fileRule);

            LogManager.Configuration = config;
        }

This code throws:

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: LayoutRenderer cannot be found: '#'

Moreover, even with a simple setting of archive every minute and a ArchiveFileName without the ${#} layout renderer, archiving seems to not be working at all.

RC2 support

Has work on RC2 support started?
If not I'll help, I'm sure a lot are starting the upgrade and anyone who depends on this will be blocked.

ConfigureExtensions means readme instructions are out of date?

Does remove ASP.NET dependency, in particular the change to ConfigureExtensions.cs, mean that this section of the readme is out of date?:

 //needed for non-NETSTANDARD platforms: configure nlog.config in your project root
  env.ConfigureNLog("nlog.config");

Should it be replaced with (It's equivalent?)

 //needed for non-NETSTANDARD platforms: configure nlog.config in your project root
  loggerFactory.ConfigureNLog("nlog.config");

NLog Extension not working for 4.5.1 or 4.6.1 frameworks

Is there a plan to get the NLog extension working if you are targeting the 4.5.1 or 4.6.1 frameworks?

Taking the example application the logging works - but if I change the project.json file to the following no logging is done:

{
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics":  "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc2-final",
    "NLog.Extensions.Logging": "1.0.0-rc2-final-2016-05-21"

  },

  "tools": {
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    }
  },

  "frameworks": {
    "net451": {
      "frameworkAssemblies": {
        "System.Web": "4.0.0.0"
      }
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "gcServer": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Filtering Logs

I am trying to implement NLog Logging in asp.net 5
The logging works but I am getting every log from the asp.net framework and would like to split these logs and my own application logs into separate log files.
I am aware that this can be done using filtering, however I am expecting the ${callsite} to represent the namespace of my logger, so cannot filter the logs.

Startup.cs:

loggerFactory.AddNLog();            
env.ConfigureNLog("nlog.config");

nlog.config:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="false" autoReload="false" internalLogFile="C:\Development\Logs\NLog_Debug.txt" internalLogLevel="Error" internalLogToConsoleError="false">
  <targets async="true">
    <target name="AspNetLogFile" xsi:type="File" fileName="C:\Development\Logs\AspNet_${date:format=yyyy-MM-dd}.log" layout="${longdate:format=yyyy-MM-dd HH:mm:ss} ${level:uppercase=true:padding=5} ${callsite} ${message} ${exception:format=Message,StackTrace}" maxArchiveFiles="30" archiveAboveSize="10485760" archiveNumbering="Rolling" archiveEvery="Day" />
    <target name="ApplicationLogFile" xsi:type="File" fileName="C:\Development\Logs\Web_${date:format=yyyy-MM-dd}.log" layout="${longdate:format=yyyy-MM-dd HH:mm:ss} ${level:uppercase=true:padding=5} ${callsite} ${message} ${exception:format=Message,StackTrace}" maxArchiveFiles="30" archiveAboveSize="10485760" archiveNumbering="Rolling" archiveEvery="Day" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" maxLevel="Error" writeTo="ApplicationLogFile">
      <filters>
        <when condition="starts-with('${logger}','App.')" action="LogFinal" />
        <when condition="starts-with('${logger}','Web')" action="LogFinal" />
      </filters>
    </logger>
    <logger name="*" minlevel="Info" maxLevel="Debug" writeTo="AspNetLogFile" />
  </rules>
</nlog>

I have 2 project, the web application where the namespace starts with Web. eg Web.Controllers
and a class library project called App where the namespaces started with "App."

I have a base controller which as follows:

using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;


namespace App.Web.Mvc
{
    public class Controller : Microsoft.AspNet.Mvc.Controller
    {
        protected Settings Settings { get; }
        protected ILogger Logger { get; }

        public Controller(ILoggerFactory loggerFactory, IOptions<Settings> settings, IServiceProvider serviceProvider)
        {
            Logger = loggerFactory.CreateLogger(GetType().Namespace);
            Settings = settings.Value;
        }
    }
}

Calling: Logger.LogInformation("Home/Index called"); in my HomeController results in the following log:

2016-02-14 14:31:03.4450 INFO Microsoft.Extensions.Logging.Logger.Log Home/Index called

Does this setup look correct? should I expect the callsite to not be Microsoft.Extensions.Logging.Logger.Log?

ConnectionStringName not supported on NLog DatabaseTarget with NetCore

Hi,
I get an error:

2016-08-24 10:32:55.0195 Error Error has been raised. Exception: System.NotSupportedException: Parameter connectionStringName not supported on DatabaseTarget

Can't i use
<target name="database" xsi:type="Database" connectionStringName="logConnection">
in a Core app?

logConnection is configured in the JSON config file.

Also for

  <target name="file"
      xsi:type="File"
      fileName="${basedir}/Logs/${shortdate}.txt"
      layout="${date:format=dd.MM.yyyy hh\:mm\:ss} [${level}] ${newline} ${newline} [${callsite}] ${newline} ${message} ${newline} ${newline} ${stacktrace} ${newline} ${newline}${exception:format=ToString} ${newline} ${newline}" />

I don't get any output.

Thanks

Adding extended properties in NLog in .net core

I am using NLog for logging messages in .net core.
I have added NLog in StartUp.cs as follows:
loggerFactory.AddNLog();

Then logging is done as follows:

public Controller(ILogger<Controller> logger)
{
   this.logger = logger;
}

[HttpGet]
public IEnumerable<string> Get()
{
   logger.LogInformation("Message");
   return new string[] { "value1", "value2" };
}

I want to log other properties to my message.
I am referring to Properties of LogEventInfo class of NLog.
How can I pass extended properties to LogInformation() method.

nlog.config - Using XML NameTag "Variable" does not seems to work

Using this nlog.config template from https://github.com/NLog/NLog.Extensions.Logging/blob/master/examples/aspnet5application/src/aspnet5application/nlog.config

I tried to specify a custom ${logFile} variable as shortcut, I get this "An exception of type 'NLog.NLogConfigurationException' occurrend in NLog.dll but was not handled in user code. Additional information: Error when setting property 'FileName' on File Target[file]" exception error.

--snip--
image
--snip--

env.WebRootPath broken for IIS publishing in Core RTM?

It looks like the RTM alpha update works for local debugging of an IIS site, but when I publish to a remote server using Web Deploy, NLog can't find the config file because the Directory.GetParent method fails while calling env.ConfigureNLog("nlog.config").

This appears to be because the env.WebRootPath is not where the code expects (likely because they changed the folder structure from layered to flat?), but I haven't looked closely enough to be 100% sure.

For now, my workaround is setting the env.WebRootPath to a hack subdirectory underneath the flat root path (e.g. C:\MySite\NLogHack will turn into C:\MySite & then find NLog.config).

asp.net Core $(callsite} rears its head

I'm working on a asp.net core project targeting .net 4.6.1. My ${callsite} token always renders

Microsoft.Extensions.Logging.Filter.Internal.FilterLogger.Log

Here's my startup.configure:

    loggerFactory.WithFilter(
                    new FilterLoggerSettings
                    {
                        { "Microsoft", LogLevel.Warning },
                        { "System", LogLevel.Warning }
                    }
                    ).AddNLog(); 
                env.ConfigureNLog(@".\nlog.config");

                ILogger log = loggerFactory.CreateLogger("Configure");
                log.LogInformation("Startup");

and my 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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd nlog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Error" 
      internalLogFile="c:\temp\nlog-internal.log" >
  <targets>

    <target xsi:type="ColoredConsole" name="console"/>

    
    <!--Writing events to the a file with the date in the filename.--> 
    <target xsi:type="File" name="debugFile" fileName="${basedir}/logs/debug-${shortdate}.log"
            layout="${longdate}|${uppercase:${level}}|${callsite:className=true:methodName=true}|${message}" />
    
    <target xsi:type="Database" name="activity"
            connectionString="Data Source=mydb;Initial Catalog=MPPV3;User ID=meomy;Password=supersecret;Trusted_Connection=False"
            dbProvider="System.Data.SqlClient"
            commandType="Text"
            commandText="INSERT INTO dbo.MPP_ActivityLog
            (Created, Level, Source, Machine, Message) 
            VALUES 
            (@Created, @Level, @Source, @Machine, @Message);">

      <parameter name="@Created" layout="${date}" />
      <parameter name="@Level" layout="${level}" />
      <parameter name="@Source" layout="${callsite:className=true:methodName=true}" />
      <parameter name="@Machine" layout="${machinename}" />
      <parameter name="@Message" layout="${message}" />
    </target>

    <target xsi:type="Database" name="incident"
            connectionString="Data Source=mydb;Initial Catalog=MPPV3;User ID=meomy;Password=supersecret;Trusted_Connection=False"
            dbProvider="System.Data.SqlClient"
            commandType="Text"
            commandText="INSERT INTO dbo.MPP_IncidentLog
            (Created, Source, Machine, Message, StackTrace) 
            VALUES 
            (@Created, @Source, @Machine, @Message, @Stacktrace);">

      <parameter name="@Created" layout="${date}" />
      <parameter name="@Source" layout="${callsite}" />
      <parameter name="@Machine" layout="${machinename}" />
      <parameter name="@Message" layout="${message}" />
      <parameter name="@Stacktrace" layout="${exception:format=ToString}" />
    </target>

  </targets>

  <rules>
    <!--<logger name="*" levels="Info,Warn,Debug,Trace" writeTo="console" />-->
    <!--<logger name="*" levels="Debug,Warn,Info" writeTo="debugFile" />-->
    <logger name="*" levels="Info,Trace" writeTo="activity" />
    <logger name="*" levels="Error" writeTo="Incident" />
    <logger name="*" levels="Trace" writeTo="console" />
  </rules>
</nlog>

My nLog assemblies....
image
2016-11-17_17-03-44

EventId formatting

I've been playing around with NLog and ILogger provided by ASP.NET Core. In the current implementation, the NLogLogger just sticks the EventId into a property of the LogEventInfo.

When this is rendered, it just calls ToString(), resulting in the following output:
|INFO|Microsoft.Extensions.Logging.EventId|

Before adding it to the properties, it should be formatted. i.e. something like this:

eventInfo.Properties["EventId"] = string.IsNullOrEmpty(eventId.Name) ? $"{eventId.Id}" : $"{eventId.Name}-{eventId.Id}";

Fail to get nuget package

When I add dependency in project.json:

"dependencies": {
"NLog.Extensions.Logging": "1.0.0-*"
}

The output windows shows messsages like:

log : Retrying 'FindPackagesByIdAsyncCore' for source 'https://dotnet.myget.org/F/nuget-beta/vsix/FindPackagesById()?id='NLog.Extensions.Logging''.
log : Response status code does not indicate success: 404 (Not Found).
log : Retrying 'FindPackagesByIdAsyncCore' for source 'https://dotnet.myget.org/F/nuget-beta/vsix/FindPackagesById()?id='NLog.Extensions.Logging''.
log : Response status code does not indicate success: 404 (Not Found).
error: Failed to retrieve information from remote source 'https://dotnet.myget.org/F/nuget-beta/vsix/FindPackagesById()?id='NLog.Extensions.Logging''.
error: Response status code does not indicate success: 404 (Not Found).
error: Failed to retrieve information from remote source 'https://dotnet.myget.org/F/nuget-beta/vsix/FindPackagesById()?id='NLog.Extensions.Logging''.
error: Response status code does not indicate success: 404 (Not Found).

My project is ASP.NET Core 1.1

I try to create a new ASP.NET Core Empty project and fails too.

The same thing when I try to do this in Package Manage Console:

PM> Install-Package NLog.Extensions.Logging -Pre
Install-Package : The V2 feed at 'https://dotnet.myget.org/F/nuget-beta/vsix/FindPackagesById()?id='NLog.Extensions.Logging'' returned an unexpected status code '404 Not Found'.
At line:1 char:1
Install-Package NLog.Extensions.Logging -Pre
> CategoryInfo : NotSpecified: (:) [Install-Package], FatalProtocolException
> FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

.NET Core: Target cannot be found: 'Network'

when running project from https://github.com/NLog/NLog.Extensions.Logging/tree/master/examples/aspnet-core-example/src/aspnet-core-example


Added Network target

<target name="json" 
        xsi:type="Network"
        address="udp://127.0.0.1:1999"
        layout='{ "time":"${longdate}","level":"${level}","file":"${json-encode:jsonEncode=true:inner=${callsite:className=false:fileName=true:includeSourcePath=true:methodName=false}}","message":"${message:withException=False} ${onexception:${exception:format=Message}}", "method":"${callsite:className=true:fileName=false:includeSourcePath=false:methodName=true}" }'/>

also updated writeTo

<logger name="*" minlevel="Trace" writeTo="ownFile-web,json" />

ERROR

internal-log.txt

2016-05-25 05:34:17.3960 Error Error in Parsing Configuration File. Exception: NLog.NLogConfigurationException: Exception occurred when loading configuration from NLog.config ---> System.ArgumentException: Target cannot be found: 'Network'
   at NLog.Config.Factory`2.CreateInstance(String name)
   at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
   at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
   --- End of inner exception stack trace ---
2016-05-25 05:34:17.3960 Error Error has been raised. Exception: System.ArgumentException: Target cannot be found: 'Network'
   at NLog.Config.Factory`2.CreateInstance(String name)
   at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
   at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)


logging to text file works if "Network" target removed from nlog.config


.net core cli info

Product Information:
Version: 1.0.0-preview1-002702
Commit Sha: 6cde21225e

Runtime Environment:
OS Name: Windows
OS Version: 10.0.10586
OS Platform: Windows
RID: win10-x64

Why named the extensions class "AspNetExtensions"?

I don't think it's a good idea to name the extensions class as "AspNetExtensions". Because NLog also can be use in other back end applications than website.

Probably the name "NLogExtensions" would be better?

Its not logging in Event Log

Hello Team,

I am using NLog.Extensions.Logging 1.0.0-rtm-alpha5 version in ASP.NET Core application when I use the SQL Server its works fine. But when I tried to put the log into windows event log it's not putting log there. Is there any problem with configuration. Following is my nlog.config.

image

Let me know if I'm doing anything wrong with the configuration.

Can't install extension under .NET 4.6.1 with RTM Core files

I have a .NET 4.6.1 class library. I've added the Microsoft.Extensions.Logging.Abstractions RTM assemblies to the library. I have also added NLog version 4.3.5. When trying to add the NLog.Extensions.Logging alpha version I get the below error:

writeErrorStream : True Exception : System.Exception: Failed to add reference to 'System.Xml.XmlSerializer'. Please make sure that it is in the Global Assembly Cache. TargetObject : CategoryInfo : NotSpecified: (:) [Install-Package], Exception FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo PipelineIterationInfo : {0, 1} PSMessageDetails :

I have made sure that my class library contains a reference to System.Xml.Serialization.

Any ideas on what the actual error is?

Thanks

marc

Add console example

Add an console application with log configuration in examples folder

VS2015 or VS2017

Callsite renderer not working for Asp.net Core/5

Hi,

I'm working on an Asp.net Core/5 RC1 Update 1 project. I'm trying to put the call site for all messages into the log but using the callsite renderer is appearing not to work. I just get an empty string in the log. Is there any known work around that I can use in order to make this work?

Thanks

Config per environment?

Is there a recommended way of setting the config per environment?

Example:
Development: Min level = trace, file name = pathX/log.txt
Staging/Production: Min level = info, file name = pathY/log.txt

NLogLogger adds properties with a "." which doesn't work with elasticsearch

Hi,

I'm facing some problems where the NLogLogger automatically adds the EventId from the .NET Core log to the properties of NLogEvent.

eventInfo.Properties["EventId.Id"] = eventId.Id;
eventInfo.Properties["EventId.Name"] = eventId.Name;
eventInfo.Properties["EventId"] = eventId;

When using ElasticSearch as the final destination with the RabbitMQ Target as the Nlog Target I'm getting issues where property names can't contain a ".".

Can we adjust this by using a "_" instead?

Best Regards,

Mark Monster

Error has been raised. Exception: System.ArgumentException: Target cannot be found: 'Database'

Getting following error when trying log error to database . I am using Nlog.web.aspnetcore

Error in Parsing Configuration File. Exception: NLog.NLogConfigurationException: Exception occurred when loading configuration from NLog.config ---> System.ArgumentException: Target cannot be found: 'Database'
   at NLog.Config.Factory`2.CreateInstance(String name)
   at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
   at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
   --- End of inner exception stack trace ---
2016-07-09 18:47:00.1213 Error Error has been raised. Exception: System.ArgumentException: Target cannot be found: 'Database'
   at NLog.Config.Factory`2.CreateInstance(String name)
   at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
   at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)

syslog?

Any support for syslog logging yet?

Move NLog config into appsettings.json, or alternatively, add extension method for ConfigurationBuilder to load NLog config

.config files have been mostly dropped from .net core, in favour of the appsettings.json file. Sections can be added to the file, and read into a strongly typed class used in your configuration (example http://www.codeproject.com/Tips/1005242/Using-nLog-with-ASP-NET-vNext). Alternatively you could keep the .config file, and add an extension method for ConfigurationBuilder, to automatically read and process it. However then you would need to get the NLog config from the IConfigurationRoot I believe (still checking this part out).

Issue: Archiving doesn't work on .Net Core Centos deploy

To reproduce

  1. create a basic .net core Web API application
  2. add NLog.Extensions.Logging
  3. configure logging for archiving, as follows
<?xml version="1.0"?>
<nlog  autoReload="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <variable name="DefaultLayout"
          value="${longdate} [${threadid}][${callsite}] ${level:upperCase=true}: ${message} ${ExceptionFormat}" />
  <targets async="true">
    <target name="DefaultFileTarget"
            xsi:type="File"
            fileName="${basedir}/logs/feedapi.current.log"
            layout="${DefaultLayout}"
            archiveEvery="Day"
            archiveFileName="${basedir}/logs/api.{##}.log"
            archiveNumbering="DateAndSequence"
            archiveDateFormat="yyyyMMdd"
            archiveAboveSize="50000000"
            maxArchiveFiles="50" />
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" writeTo="DefaultFileTarget" />
  </rules>
</nlog>
  1. Set up application logging as follows:
    [HttpGet] public string Get() { _log.Info("Hello world"); return "Hello world"; }
  2. Deploy to a Centos machine. I used Apache set up as a reverse proxy as the front end, and deployed the application simply by executing dotnet restore -> dotnet run in its root directory..
  3. Get an API client to call the Get method you just created a few times in a row

Expected behavior

  • Hello World written multiple times to the same log file

Actual behavior

  • As many log files created as GET requests made. NLog archives with every new log entry.

Notes

This issue doesn't occur on my Windows dev box. NLog.Extensions.Logging works fine there.

I'm not sure whether this issue belongs to NLog.Extensions or to Dotnet Core, but I thought it would be worth bringing it to your attention.

Thanks! : )

No log files created on Ubuntu 14.04

I couldn't make NLog extensions to work on my Ubuntu 14.04 machine. We use dotnet core (1.0.0-preview2-002913) serving with Kestrel. There are 2 other developers (one of them has Windows 10 and the other one has OSX) working on the exact same snapshot on the project (same code base and same nlog.config etc) and it's all working fine for them.

There are no actual log files, and no internal logging file on ubuntu

Below is the 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">

    <targets>
        <target xsi:type="File" name="allfile" fileName="${basedir}/all-${shortdate}.log"
            layout="${longdate}|${logger}|${uppercase:${level}}|${message}${newline}${exception:format=ToString,StackTrace}${newline}" />
        <target xsi:type="File" name="errorsfile" fileName="${basedir}/errors-${shortdate}.log"
            layout="${longdate}|${logger}|${message}${newline}${exception:format=ToString,StackTrace}${newline}" />
    </targets>
    <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allfile" />
        <logger name="*" minlevel="Error" writeTo="errorsfile" />
    </rules>
</nlog>

And this is the startup configuration:

            loggerFactory
                .AddConsole()
                .AddNLog();

ConfigureNLog - defaults to an unexpected path to load config file. ( DNX - RC1 )

Type : Bug
NLog version:
"NLog": "4.4.0-alpha1",
"NLog.Config": "4.3.0-beta1",
"NLog.Extensions.Logging":"1.0.0-rc1-final-2016-02-06"

Platform:
Windows Server 2012 R2
Microsoft. IIS 8 ( http platform handler)
Microsoft HTTP Platform Handler 1.2
DNX / net runtime : dnx-clr-win-x86.1.0.0-rc1-update1

  • What is the current result? .ConfigureNLog seems to use the wrong relative path
  • What is the expected result? The relative path should default to "approot\src"
  • Are there any work arrounds? YES (move the config file )

Hope this isn't a duplicate. This issue only arises AFTER deployment. I am using "ConfigureNlog" to pass an external Nlog XML config file. In Development this file is in my Visual Studio project root ( same folder as package.json, project.json, etc.) In Development everything works fine. When I deploy to the server, the new DNX production server folder structure is according to the new MS "standard":

   [drive]:\[SomeRoot]\
   [drive]:\[SomeRoot]\approot\
   [drive]:\[SomeRoot]\wwwroot\
   [drive]:\[SomeRoot]\logs\

By default Visual Studio copies my nlog.prod.config file to

   [drive]:\[SomeRoot]\approot\src\[project name]

NLOG fails because it by default want to look for nlog.prod.config in

   [drive]:\[SomeRoot]

This appears to be contrary to the new way that DNX projects are structured. "SomeRoot" is typically entirely empty.

I know this an "RC1" environment , but this really seems to be a bug.

My source code is below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
app.AddNLogWeb();
if (env.IsDevelopment())
{
** env.ConfigureNLog("nlog.dev.config"); **

If anything isn't clear, please let me know. Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.