Giter VIP home page Giter VIP logo

autofac.extras.nlog's Introduction

Autofac Loggging Module for NLog

Build status

Nuget package available, to install run the following command;

Install-Package Autofac.Extras.NLog

Register NLogModule to Autofac

It attaches to Component Registration and creates logger for requested type.

containerBuilder.RegisterModule<NLogModule>();

Register SimpleNLogModule to Autofac

It is useful when ILogger resolved from Service Locator.

containerBuilder.RegisterModule<SimpleNLogModule>();

NLogModule and SimpleNLogModule supports both constructor and property injection.

  • Constructor sample
public class SampleClassWithConstructorDependency : ISampleInterface
{
    private readonly ILogger _logger;

    public SampleClassWithConstructorDependency(ILogger logger)
    {
      _logger = logger;
  }        
}
  • Property Sample
public class SampleClassWithPropertyDependency : ISampleInterface
{
   public ILogger Logger { get; set; }
}
  • Service Locator Sample
 public class SampleClassToResolveLoggerFromServiceLocator : ISampleClass
    {
        private readonly ILogger _logger;
        
        public SampleClassToResolveLoggerFromServiceLocator(ILifetimeScope serviceLocator)
        {
            _logger = serviceLocator.Resolve<ILogger>();
        }
    }

autofac.extras.nlog's People

Contributors

anth12 avatar bugthesystem avatar cnboland avatar janv8000 avatar previousdeveloper avatar shoftee 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

autofac.extras.nlog's Issues

.Net Core 2.0 - Warning NU1701

I started a Project with Core 2.0 and after installing the Nuget package, i have a warning in VS2017 that the package is for .Net 4.6.1 and maybe not compatible.

It is running fine, so there is no Problem with any code here. Could you create a new Nuget Release with Core compatability?

NLogger.Trace not implemented

All the standard Log Levels are represented, except 'Trace'. In other words, when using this module, you can do:
_logger.Debug("My debug message");

But you cannot do:
_logger.Trace("My trace message");

Why is this? I can happily fix and do a pull request, if you like.

Latest Autofac (8.0.0) is not supported

Build warning on projects using latest Autofac:

NU1608: Warning As Error: Detected package version outside of dependency constraint: Autofac.Extras.NLog 4.0.1 requires Autofac (>= 6.0.0 && < 8.0.0) but version Autofac 8.0.0 was resolved.

NullLogger

Hi, it is possible to add NullLoggerClass which implements ILogger (without method implementations)?
It can be useful in some cases (e.g. tests) when you are injecting ILogger in constructor and logs are not needed in this case.

v1.2.2 causes code analysis error

Hi,

First off, thanks for making this library, it's been very valuable in integrating Autofac to my existing project with NLog. I upgraded to 1.2.2 via Nuget today, and have gotten the following error when building my solution:

CA0001 Error Running Code Analysis CA0001 : Could not find type 'NLog.LoggerReconfiguredDelegate' in assembly 'Autofac.Extras.NLog, Version=1.2.2.0, Culture=neutral'. Errors and Warnings

I was wondering if there was any troubleshooting you'd suggest to fix this, or should I just rollback to 1.2.1 for now? Thanks!

Reference not found

Hello!

I'm having a problem with your library. I have a ASPNET Core project using net462, and a test project using net462 too. There is a method in my web project that injects NLogModule and if I call this method in a test I get an error.

Message: System.IO.FileLoadException : Could not load file or assembly 'Autofac, Version=2.2.4.900, Culture=neutral, PublicKeyToken=17863af14b0044da' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

If I comment the line, rebuild and test again, the error goes away. ๐Ÿค”

Warning [NU1608] Detected package version outside of dependency constraint

A new version Autofac 7.0.1 has just been released

I would like mitigate the warning: Autofac.Extras.NLog 4.0.0 requires Autofac (>= 6.0.0 && < 7.0.0) but version Autofac 7.0.1 was resolved. Can you please extend range of supported versions.

<PackageReference Include="Autofac" Version="[6.0.0, 7.0.0)" />

callsite

When you configure nlog to log the 'callsite', instead of the original calling function, you see Autofac.Extras.NLog.LoggerAdapter.Info.

Example: in nlog config specify target with callsite variable:

in code:
_log.Info("Test");

result:
2017-05-31 09:11:16.2194 17 Autofac.Extras.NLog.LoggerAdapter.Info INFO Test

overwrites my registration

Hello,

In some cases I want to register my own logger (with a specific logger name) for a specific generic class (my generic class has a very ugly full name to see on log files) but this module overwrites my registration.

1- How can i use specific logger names for specific classes (still accepting ILogger as a parameter on class constructor).
2- Can checking already existing registration on "NLogMiddleware" class help?

Incompatible with NLog 2.0 api

NLog's API changed a bit with version 2.0, eg. the LoggerReconfiguredDelegate was replaced with the built-in EventHandler.

But the nuget package declares its dependency for NLog without upper limit:
<dependency id="NLog" version="1.0.0.505" />

Doing a Update-Package NLog will pull-down the latest version (3.x), no longer containing the LoggerReconfiguredDelegate.

The NLog dependency should be changed as follows:
<dependency id="NLog" version="(1.0.0.505,2.0]" />

Write Database

Hi,
I was trying to setup my project ASP.NET MVC with .Net Framework 4.7.2 to use NLog and Autofac.
It just strange that , when writing a log to a file it was working as expected, but when trying to log in database it doesn't log anything.

Here is my config in DI:

 // Register NLog
 builder.RegisterModule<NLogModule>();
builder.RegisterType<LoggerFactory>().As<ILoggerFactory>().SingleInstance();
builder.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>)).SingleInstance();

var container = builder.Build();

var loggerFactory = container.Resolve<ILoggerFactory>();

loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });

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"
  throwConfigExceptions="true">
  <extensions>
    <add assembly="NLog.Extended" />
  </extensions>
  <targets>
    <!-- database target -->
    <target name="database"
     xsi:type="Database"
     connectionStringName="ExceptionLogConnectionString"
     commandType="StoredProcedure"
     commandText="[dbo].[InsertLog]">
      <parameter name="@level" layout="${level}" />
      <parameter name="@callSite" layout="${callsite}" />
      <parameter name="@type" layout="${exception:format=type}" />
      <parameter name="@message" layout="${exception:format=message}" />
      <parameter name="@stackTrace" layout="${exception:format=stackTrace}" />
      <parameter name="@innerException"
                  layout="${exception:format=:innerFormat=ShortType,Message,Method:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}" />
      <parameter name="@additionalInfo" layout="${message}" />
    </target>
  </targets>

  <rules>
    <!-- database logger -->
    <logger levels="Error,Warn,Fatal" name="databaseLogger" writeTo="database"/>
  </rules>
</nlog>

Im trying to instantiate it like this inside the controller:

public class TestController {
private readonly ILogger _logger;

    public TestController(ILogger logger){
         _logger = logger;
    }
}

or like this:

public class TestController {
private readonly ILogger<TestController> _logger;

    public TestController(ILogger<TestController> logger){
         _logger = logger;
    }
}

But still doesn't log anything, Can anyone please guide me?

PS:

This code was able to insert log in database, but not the above setup

// get a Logger object and log exception here using NLog. 
// this will use the "databaseLogger" logger from our NLog.config file
NLog.Logger logger = NLog.LogManager.GetLogger("databaseLogger");

// add custom message and pass in the exception
logger.Error(ex, "Whoops!");

Thanks,
Jonathan

Does SimpleNLogModule exist?

Hello and thank you for this tool. I have a problem with resolving ILogger with IServiceProvider. My implementation is pretty simple:

    public class ServiceProvider : IServiceProvider
    {
        private readonly ILifetimeScope scope;

        public ServiceProvider(ILifetimeScope scope)
        {
            this.scope = scope;
        }

        public object GetService(Type serviceType)
        {
            return scope.Resolve(serviceType);
        }
    }

and this is registration part:

var builder = new ContainerBuilder();
builder.RegisterModule<NLogModule>();
builder.RegisterType<ServiceProvider>().As<IServiceProvider>();

Types registered with RegisterType are resolved well, but when I try to resolve ILogger I got "The requested service 'NLog.ILogger' has not been registered" exception. If ILogger is injected as constructor parameter then is resolved well as part of ASP.NET DI. What am I doing wrong?

Your Readme says that there is SimpleNLogModule that "is useful when ILogger resolved from Service Locator". But it looks like it doesn't exist any more.

Question: Why not using NLog.ILogger

Why did you create an extra Interface for the ILogger? I changed it to global::NLog.ILogger so i do not have to Strongname it in my Application. Is it why you commented "//TODO: UPDATE TO USE NLOG:INTERFACE Package (Fork and solve nlog.interface issues)" in the ILogger?

Unfortune method to log exception

ILogger interface has unfortune method void Error([Localizable(false)] string message, Exception exception). It's fine when I pass Exception class, but when I pass any other exception C# compiler choose different method to use: void Error<TArgument>([Localizable(false)] string message, TArgument argument).

The effect is that exception details are not logged. I suggest to change order of parameters and deprecate original method.

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.