Coder Social home page Coder Social logo

ninject.extensions.logging's Introduction

Ninject

Build status codecov NuGet Version NuGet Downloads

Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.

Write your code so it's flexible...

public class Samurai {
    public IWeapon Weapon { get; private set; }
    public Samurai(IWeapon weapon) 
    {
        this.Weapon = weapon;
    }
}

...and let Ninject glue it together for you.

public class WarriorModule : NinjectModule
{
    public override void Load() 
    {
        this.Bind<IWeapon>().To<Sword>();
    }
}

Features:

  1. Focused. Too many existing dependency injection projects sacrifice usability for features that aren't often necessary. Each time a feature is added to Ninject, its benefit is weighed against the complexity it adds to everyday use. Our goal is to keep the barrier to entry - the baseline level of knowledge required to use Ninject - as low as possible. Ninject has many advanced features, but understanding them is not required to use the basic features.

  2. Sleek. Framework bloat is a major concern for some projects, and as such, all of Ninject's core functionality is in a single assembly with no dependencies outside the .NET base class library. This single assembly's footprint is approximately 85KB when compiled for release.

  3. Fast. Instead of relying on reflection for invocation, Ninject takes advantage of lightweight code generation in the CLR. This can result in a dramatic (8-50x) improvement in performance in many situations.

  4. Precise. Ninject helps developers get things right the first time around. Rather than relying on XML mapping files and string identifiers to wire up components, Ninject provides a robust domain-specific language. This means that Ninject takes advantage of the capabilities of the language (like type-safety) and the IDE (like IntelliSense and code completion).

  5. Agile. Ninject is designed around a component-based architecture, with customization and evolution in mind. Many facets of the system can be augmented or modified to fit the requirements of each project.

  6. Stealthy. Ninject will not invade your code. You can easily isolate the dependency on Ninject to a single assembly in your project.

  7. Powerful. Ninject includes many advanced features. For example, Ninject is the first dependency injector to support contextual binding, in which a different concrete implementation of a service may be injected depending on the context in which it is requested.

Everything else is in Extensions

Yes, sounds slim and focused, but where is the support for all the features that the competitors have?

Generally, they are maintained as specific focused extensions with owners who keep them in sync and pull in new ideas and fixes fast. These are summarized on the extensions section of the project website. Most are hosted alongside the core project right here.

License

Ninject is intended to be used in both open-source and commercial environments. To allow its use in as many situations as possible, Ninject is dual-licensed. You may choose to use Ninject under either the Apache License, Version 2.0, or the Microsoft Public License (Ms-PL). These licenses are essentially identical, but you are encouraged to evaluate both to determine which best fits your intended use.

Refer to LICENSE.txt for detailed information.

Changes history

Resources

ninject.extensions.logging's People

Contributors

dependabot[bot] avatar estiller avatar iappert avatar idavis avatar jamesmanning avatar kevindaub avatar lyrex avatar martin308 avatar mikewyatt avatar remogloor avatar scott-xu avatar snebjorn 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

Watchers

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

ninject.extensions.logging's Issues

Log4Net implementation of Debug(string message) broken

Unlike the direct access to log4net:

var message = "foo { bar";

var logger = log4net.LogManager.GetLogger("Log4NetLoggerTest");
logger.Debug(message);

which results in the following log entry:

2011-08-29 10:02:02,071 [9] DEBUG Log4NetLoggerTest foo { bar

using log4net through Ninject's extension:

using (IKernel kernel = new StandardKernel())
{
var loggerFactory = kernel.Get<ILoggerFactory>();
loggerFactory.GetCurrentClassLogger().Debug(message);
}

results in:

2011-08-29 13:25:45,521 [10] DEBUG TestApp.MainWindow <log4net.Error>Exception during StringFormat: Input string was not in a correct format. <format>foo { bar</format><args>{}</args></log4net.Error>

Even worse, when using the ILogger's Trace method there is a first chance exception of type 'System.FormatException' in mscorlib.dll

log4net 1.2.11.0 support

Since the latest version of log4net was pushed to NuGet (December 21, 2011), this extension is broken. Can you push a update to Ninject.Extensions.Logging.Log4Net project to use log4net 1.2.11.0 to nuGet?

By broken, I mean even if I force nuGet to install log4net 1.12.10 that version will get overwritten with the latest version because the dependency for log4Net is set to >= 1.0.4.

Bizarre dependency requirements

I do not mean to be rude, but creating package dependencies like, "Ninject (>= 3.2.0 && < 3.3.0)" for your 3.2.3 release is beyond frustrating. I am trying to use Ninject, Ninject.Extensions.Logging, Ninject.Extensions.Logging.Serilog, Ninject.Extensions.Interception, Ninject.Extensions.Interception.DynamicProxy, Ninject.Extensions.Factory, and Ninject.Extensions.Conventions. My initial project used Ninject 3.3.4, the latest, but a dependency I have yet to identify wanted Ninject 3.3.3. So I downgraded, but all the other Ninject projects with version 3.3.3 or less wanted 3.3.4. Your 3.3.0 wants 3.3.4. Attempting to downgrade Ninject.Extensions.Logging to 3.2.3 results in this narrow window, and so do your other earlier releases. Logging should not be so version dependent. This is DLL hell. Why can't all the Ninject projects just use the same release number and be compatible with each other?

Unable to inject ILogger into MvcApplication (asp.net mvc)

I'm using ninject.extensions.logging and ninject.extensions.log4net. I can confirm I have logging setup properly because all my controllers/other classes in the project are able to log. But for some reason I can't get ninject to inject an ILogger into the MvcApplication class in the global asax file. Here's the code

public class MvcApplication : System.Web.HttpApplication
{
    [Inject]
    public ILogger logger { get; set; }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        log4net.Config.XmlConfigurator.Configure();

        //Tell the world we started up!
        logger.Info("Application Started Successfully!");
    }

    protected void Application_Error()
    {
        var error = Server.GetLastError();
        logger.Error(error,"Unhandled Exception In Web Application",new object[]{});
    }
}

as you can see the ILogger is being injected with the [Inject] attribute as a property. But I always get a null reference when I try and use it from inside this class.

Dependency Injection Using Ninject, ILoogerFactory, Serilog

Apologies, for raising an issue... this is just a question:

I want to implement logging, using Serilog in my ASp.Net MVC Framework application. Please not that it is not a core application, so LoggerFactory is not automatically being injected into the program.

This is the tutorial explaining how everythign is done in ASP.Net MVC Core:

  1. Add Serilog Nuger Packages

"Serilog": "2.2.0",
"Serilog.Extensions.Logging": "1.2.0",
"Serilog.Sinks.RollingFile": "2.0.0",
"Serilog.Sinks.File": "3.0.0"

  1. Add the following lines to the constructor of your Startup class

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "log-{Date}.txt"))
.CreateLogger();

  1. Add the following line to the configure method of your Startup class

loggerFactory.AddSerilog();

  1. Inject the logger to your services or controllers

public class Chat : IChat
{
// Instancia del logger
ILogger logger;

    // Injectamos el logger en el constructor
    public Chat(ILogger logger)
    {
        this.logger = logger;
    }

Now this explanation is for .Net Core, I don't know how I should implement it in my MVC project...

I don't know how to Inject the LoggerFacory in my startup class... I can initialize it in my Startup and Add Serilog to it, but then how can I inject the Logger into my Constructor?

Old versions supported

Hello, this is more question than an issue.

I'm trying to add Serilog logging support for ninject via NuGet to my project. It strikes me why this extension does not support the latest version of Ninject and Serilog?

  • Ninject
    • newest: 3.3.4
    • supported: 3.2.2
  • Serilog
    • newest: 2.6.0
    • supported: 1.5.14

Don't we loose some important functionality by that? It strikes me that both dependencies are so old.

Thanks.

EDIT: Serilog 2.x is not supported, which in turn prevents us to use Serilog.Sinks extensions.

LoggerFactoryBase should be abstract

Currently ILogger gets bound twice, once when Ninject loads LoggerFactoryBase and again when NLogModule calls base.Load(). In the 2.0.0.0 version of Ninject, this is not a problem, as injecting a ILogger when multiple bindings exist works even though a single ILogger cannot be created on it's own.

Since this change to Target in Ninject, injecting a single object when multiple bindings exist causes an ActivationException.

The easiest fix would to to make LoggerFactoryBase abstract or have NLogModule not call super.Load().

A test program (with both Ninject.Extensions.Logging and Ninject.Extensions.NLog referenced) illustrating the the problem:

using System;
using Ninject;
using Ninject.Extensions.Logging;
using Ninject.Modules;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            StandardKernel kern = new StandardKernel(new MyMod());
            try
            {
                var turtle = kern.Get<Turtle>();
                Console.WriteLine("got turtle");
            }
            catch (ActivationException)
            {
                Console.WriteLine("could not get turtle =(");
            }
            try
            {
                var logger = kern.Get<ILogger>();
                Console.WriteLine("got logger");
            }
            catch (ActivationException)
            {
                Console.WriteLine("could not get logger");
            }
        }
        private class MyMod : NinjectModule
        {
            public override void Load()
            {
                Bind<Turtle>().ToSelf();
            }
        }
        private class Turtle
        {
            [Inject]
            public ILogger Logger { get; set; }
        }
    }
}

2.0.0.0 output:

got turtle
could not get logger

Output using source checked out today:

could not get turtle =(
could not get logger

Quick Start?

Hi, I notice there are no examples or readme/intro for this project - the GitHub page link also fails as it doesn't exist (http://idavis.github.com/ninject.extensions.logging) - which makes this the "coldest" github project I've seen ;-) In the source code, I only find a blank unit test saying TODO under Log4NetTests.cs.

Would anyone think it's useful to contribute an intro with the very basics of what you need to get started with ninject logging extensions in their codebase? Even just a quick sales pitch.
I'm looking at the source now, and feel that even a very short "Quick Start" would be useful.

I gather I need to instantiate a log4netModule and from there, I can just put
[Inject] public ILogger Logger { get; set; } in any of my classes. That's my guess, a quick README to confirm it would be sweet.

Named loggers?

ILoggerFactory needs a GetLogger method that takes in an arbitrarily logger name as a string. It currently requires that loggers be created from a specific type.

I have a system with a class where I want a specific method to log to a separate logger, while the rest of the class logs to the "main" log. The reason is that this method outputs a large number of logging events that I don't want to clutter up the main log.

ILogger injects fine, but kernel.Get<ILogger>() throws null ref

This might be "by design", but off-hand it seemed a little harsh as an end-user experience.

steps:

  • create new console app (happens to be .NET 4.5, but that's not likely important)

  • Install-Package Ninject.Extensions.Logging.Log4net

    • the NLog and NLog2 ones are likely to do the same AFAICT
  • in Main, put these 2 lines and run:

        IKernel standardKernel = new StandardKernel();
        var logger = standardKernel.Get<ILogger>();
    

throws a null ref due to Target being null (since we're asking for the instance directly, instead of having it injected into a class) in LoggerFactoryBase.GetLogger

    public ILogger GetLogger(IContext context)
    {
        return this.GetLogger(context.Request.Target.Member.DeclaringType);
    }

I'm getting a "TypeLoadException: Inheritance security rules violated by type 'Ninject.Extensions.Logging.LoggerModuleBase'" locally (unrelated to this issue AFAICT), so I haven't been able to confirm this, but a failing test for this behavior should be:

    [Fact]
    public void CanManuallyGetILoggerInstance()
    {
        using (var kernel = this.CreateKernel())
        {
            var loggerClass = kernel.Get<ILogger>();
            loggerClass.Should().NotBeNull();
            loggerClass.Type.Should().Be(typeof(ILogger));
        }
    }

Certainly a user of ninject should have ILogger injected and never need to fetch ILogger directly (service locator anti-pattern), but in trying to use the ninject logging extension with a codebase that (unfortunately) has some places fetching instances manually, this null ref keeps it from being usable.

The least-code workaround AFAICT is rebinding ILogger (currently bound in LoggerModuleBase.Load) - here's what a modified LoggerModuleBase might look like (not sure if using the service type as a fallback is really desirable or not)

    public override void Load()
    {
        //this.Bind<ILogger>().ToMethod(context => context.Kernel.Get<ILoggerFactory>().GetLogger(context));
        this.Bind<ILogger>().ToMethod(context =>
        {
            var typeForLogger = context.Request.Target != null
                                    ? context.Request.Target.Member.DeclaringType
                                    : context.Request.Service;
            return context.Kernel.Get<ILoggerFactory>().GetLogger(typeForLogger);
        });
    }

Wrong type name in log output

Using a log4net RollingFileAppender with a layout defined as so:

<layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%type %date [%thread] %-5level - %message%newline" />
</layout>

I get different log output if logging directly through log4net or through a logger supplied by Ninject:
log4net: DogWorld.Web.Controllers.ProfileController 2013-01-03 19:14:28,815 [16] INFO - Log test
Ninject: Ninject.Extensions.Logging.Log4net.Infrastructure.Log4NetLogger 2013-01-03 19:14:28,816 [16] INFO - Log test

Abstraction Layer that Does not Abstract?

This library does abstract the difference in method names between the libraries. The largest difference between these logging libraries, however, is in the usage semantics, or how the libraries are used, primarily around the usage of structured vs unstructured loggers.

For example, I would use a Ninject.Extensions.Logging.ILogger like this if I were using Serilog:

int foo = 5;
var someObjectWithProperties = GiveItToMe();
// Normally this line would be in the constructor.  Here for the simplicity of the example.
ILogger logger = loggerFactory.GetCurrentClassLogger();
logger.Debug("I just need to log {Bar} with some {@SomeBetterName}", foo, someObjectWithProperties);

I would use the destructuring operator for any objects for which I would like to see all data. The ordering of the params is how that are mapped to the named parameters in the string when passed to the Serilog sinks. So, Bar gets the value of foo and SomeBetterName gets the value of someObjectWithProperties.

With Log4Net things would be a bit different:

int foo = 5;
var someObjectWithProperties = GiveItToMe();
ILogger logger = loggerFactory.GetCurrentClassLogger();
logger.Debug("I just need to log {0} with some {1}", foo, someObjectWithProperties.ToString());

The familiar System.String.Format semantics are used to coerce string and parameters into a single string that can travel through the appenders.

I am not arguing that the design decisions of this library are incorrect and that a heavy-weight abstraction should be created to translate between structured and unstructured logging. I like things lightweight as well.

No, this is just some documentation for myself next time I fall in love with the dream that I can use an abstraction layer to freely swap between different logging libraries without code changes. Hopefully this will snap me back into the reality that you are tied to your logging framework whether you abstract the method names or not.

Still getting SecurityException or no Binding was specified

Please provide any help. I'm using Nuget versions of ninject, ninject.logging and nlog and still getting this SecurityException:

Attempt by security transparent method 'Ninject.Extensions.Logging.NLog2.Infrastructure.NLogLogger..ctor(System.Type)' to access security critical method 'NLog.LogManager.GetLogger(System.String)' failed.

Assembly 'Ninject.Extensions.Logging.NLog2, Version=2.2.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.

I instantiate ninject in the following way:

            // Load ninject modules
            INinjectModule[] modules = { 
                new NLogModule(),
                new KernelModule(),
            };

            // Create Ninject settings
            NinjectSettings iocContainerSettings = new NinjectSettings();
            iocContainerSettings.LoadExtensions = false;

            // Create IOC container
            iocContainerKernel = new StandardKernel(iocContainerSettings, modules);

I have also tried to let ninject load modules itself but in this case i'm getting No bindings specified.

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Server Error in '/' Application.

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' could not be loaded.

=== Pre-bind state information ===
LOG: DisplayName = log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821
(Fully-specified)
LOG: Appbase = file:///c:/users/vluser3/documents/visual studio 2013/Projects/WebApplication1/WebApplication1/
LOG: Initial PrivatePath = c:\users\vluser3\documents\visual studio 2013\Projects\WebApplication1\WebApplication1\bin
Calling assembly : M7.Library.Common, Version=2.4.5862.14146, Culture=neutral, PublicKeyToken=null.

LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\users\vluser3\documents\visual studio 2013\Projects\WebApplication1\WebApplication1\web.config
LOG: Using host configuration file: C:\Users\vluser3\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root/072e5f63/d0534168/log4net.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root/072e5f63/d0534168/log4net/log4net.DLL.
LOG: Attempting download of new URL file:///c:/users/vluser3/documents/visual studio 2013/Projects/WebApplication1/WebApplication1/bin/log4net.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Build Number
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

Stack Trace:

[FileLoadException: Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) +145
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +162
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +87
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +438
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +103
System.Reflection.RuntimeAssembly.GetCustomAttributes(Boolean inherit) +33
Owin.Loader.DefaultLoader.SearchForStartupAttribute(String friendlyName, IList1 errors, Boolean& conflict) +294 Owin.Loader.DefaultLoader.GetDefaultConfiguration(String friendlyName, IList1 errors) +105
Owin.Loader.DefaultLoader.LoadImplementation(String startupName, IList1 errorDetails) +161 Owin.Loader.DefaultLoader.Load(String startupName, IList1 errorDetails) +51
Microsoft.Owin.Host.SystemWeb.OwinBuilder.GetAppStartup() +238
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +103
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func1 valueFactory) +86 System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock, Func1 valueFactory) +72
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +104
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +418
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9948312
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

Change NLog logging level at runtime?

Hello,

I'm trying to change my logging level at runtime using the following code

var c = NLog.LogManager.Configuration;
var file = c.FindTargetByName("file") as FileTarget;
if (file == null)
    return;

var rule = c.LoggingRules.FirstOrDefault(r => r.Targets.Contains(file));
if (rule == null)
    return;

if (EnableDebug)
    rule.EnableLoggingForLevel(LogLevel.Debug);
else
    rule.DisableLoggingForLevel(LogLevel.Debug);

NLog.LogManager.ReconfigExistingLoggers();

However, this doesn't work. file and rule are both found, so it reaches the if-else statement correctly but calling NLog.LogManager.ReconfigExistingLoggers(); doesn't seem to affect existing loggers.

Release of NLog3 extension package

Hi,
Is there an estimate as to when a new stable version of the NLog3 extension packages would be released?
Alternatively, is it possible to release only a version of Ninject.Extensions.Logging.nlog3 package as a stable version numbered 3.2.1 (last stable version)?
The reason I am asking is that I would like to release a package which takes dependency upon this new extension, and I cannot mark my package as stable as long as the NLog3 extension is marked as prerelease.

I truly appreciate your efforts as this is a great project and great extension.

Regards,
Eran

Push new unstable/beta version to NuGet

Since there were a few changes especially dependency-wise I wanted to ask if there are plans to push a current unstable/beta version to NuGet. If so, is there any rough date on when?

Assembly failing to load with security warnings

Started a brand new MVC3 web app project

Used NuGet to install

  • NinjectMVC3
    -NLog
    -Ninject.Extensions.Logging.NLog2

Created a new controller factory and new NinjectModule

public class ApplicationModule : NinjectModule {

        public override void Load() {

            Bind<LoggedControllerFactory>()
                .ToSelf()
                .InSingletonScope();
        }
    }

    class LoggedControllerFactory : DefaultControllerFactory {

        ILogger Logger { get; set; }

        public LoggedControllerFactory(ILogger logger) {

            Logger = logger;

            Logger.Trace("Created controller factory instance");
        }

        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) {

            Logger.Trace("Attempting to create controller instance");

            IController c = base.GetControllerInstance(requestContext, controllerType);

            Logger.Trace("Created controller instance {0}", controllerType.ToString());

            return c;
        }
    }

///Ninject.MVC3.cs
private static void RegisterServices(IKernel kernel)
        {
            kernel.Load(Assembly.GetExecutingAssembly());

            IControllerFactory factory = kernel.Get<LoggedControllerFactory>();

            ControllerBuilder.Current.SetControllerFactory(factory);
        }  

Got this error when running the application.

Attempt by security transparent method 'Ninject.Extensions.Logging.NLog2.Infrastructure.NLogLogger..ctor(System.Type)' to access security critical method 'NLog.LogManager.GetLogger(System.String)' failed.

Assembly 'Ninject.Extensions.Logging.NLog2, Version=2.2.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.

Am I missing something?

Update or New Serilog implementation

The current version used for Serilog is over 2 years old. Some extensions (Serilog.Sinks.MSSqlServer in my case) require >= 2.0.

Would you consider a pull request to either update the version of the current or to create a Serilog2 package that supports >= 2.0 (and >= .net45)?

Problems running on XP?

Hi

I have VS 2010, .net 4.0 installed and I am getting this error

System.IO.FileLoadException was unhandled
Message=Could not load file or assembly 'Ninject.Extensions.Logging.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
Source=mscorlib
FileName=Ninject.Extensions.Logging.dll
FusionLog=""
StackTrace:
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadFrom(String assemblyFile)
at Ninject.Modules.AssemblyNameRetriever.AssemblyChecker.GetAssemblyNames(IEnumerable1 filenames, Predicate1 filter) in c:\Projects\Ninject\ninject\src\Ninject\Modules\AssemblyNameRetriever.cs:line 95
at Ninject.Modules.AssemblyNameRetriever.AssemblyChecker.GetAssemblyNames(IEnumerable1 filenames, Predicate1 filter)
at Ninject.Modules.AssemblyNameRetriever.GetAssemblyNames(IEnumerable1 filenames, Predicate1 filter) in c:\Projects\Ninject\ninject\src\Ninject\Modules\AssemblyNameRetriever.cs:line 54
at Ninject.Modules.CompiledModuleLoaderPlugin.LoadModules(IEnumerable1 filenames) in c:\Projects\Ninject\ninject\src\Ninject\Modules\CompiledModuleLoaderPlugin.cs:line 81 at Ninject.Modules.ModuleLoader.LoadModules(IEnumerable1 patterns) in c:\Projects\Ninject\ninject\src\Ninject\Modules\ModuleLoader.cs:line 60
at Ninject.KernelBase.Load(IEnumerable`1 filePatterns) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 236
at Ninject.KernelBase..ctor(IComponentContainer components, INinjectSettings settings, INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 97
at Ninject.KernelBase..ctor(INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 57
at Ninject.StandardKernel..ctor(INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\StandardKernel.cs:line 46
at Main(String[] args) in Program.cs:line 17
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.NotSupportedException
Message=An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.
StackTrace:
InnerException:

If I take zip up the application and move it to any windows 7 machine it works. It just does not work on the one xp machine that I can test.

Get a new instance of ILogger each time it is injected to contain the correct LoggerName?

Hi there,

I managed to get this working and its working great, problem is though that I inject this first into my Controller which creates the TypeName part of the Ilogger as the name of my controller "TestController", this is great, so logging uses this name.

But I also inject the ILogger into a sevice layer which my controller calls, I have noticed that the service layer instance of ILogger contains "TestController" as the type name of the ILogger when it is actualy in another class / assembly and should really have the name of ProductService.

is there anyway I can fix this ?

Can I force it to inject a new instance each time ?

If I leave the Ilogger as is, in the ProductService when I write a log out it contains "TestController" as the logger name which isn't correct.

Release of NLog4 extension package

Hi,
For the same reason specified in #28, is there an estimated timeframe for the release of a "Release" NuGet package for the NLog4 extension?

Again, I truly appreciate your efforts.

Regards,
Eran

Could not load file or assembly 'log4net, Version=1.2.10.0

when running

Install-Package Ninject.Extensions.Logging.Log4net

It will update log4net version to 1.2.11 but when I run the code it will try to find 1.2.10.0

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Stack Trace:

[FileLoadException: Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
Ninject.Extensions.Logging.Log4net.Infrastructure.Log4NetLogger..ctor(Type type) in c:\Projects\Ninject\Maintenance2.2\ninject.extensions.logging\src\Ninject.Extensions.Logging.Log4Net\Infrastructure\Log4netLogger.cs:38
Ninject.Extensions.Logging.Log4net.Infrastructure.Log4NetLoggerFactory.CreateLogger(Type type) in c:\Projects\Ninject\Maintenance2.2\ninject.extensions.logging\src\Ninject.Extensions.Logging.Log4Net\Infrastructure\Log4netLoggerFactory.cs:28
Ninject.Extensions.Logging.LoggerFactoryBase.GetLogger(Type type) in c:\Projects\Ninject\Maintenance2.2\ninject.extensions.logging\src\Ninject.Extensions.Logging\LoggerFactoryBase.cs:47
Ninject.Extensions.Logging.LoggerFactoryBase.GetLogger(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject.extensions.logging\src\Ninject.Extensions.Logging\LoggerFactoryBase.cs:61
Ninject.Extensions.Logging.LoggerModuleBase.b__0(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject.extensions.logging\src\Ninject.Extensions.Logging\LoggerModuleBase.cs:26
Ninject.Activation.Providers.CallbackProvider1.CreateInstance(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Providers\CallbackProvider.cs:45 Ninject.Activation.Provider1.Create(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Provider.cs:39
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Context.cs:157
Ninject.KernelBase.b__7(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\KernelBase.cs:375
System.Linq.<>c__DisplayClass123.<CombineSelectors>b__11(TSource x) +32 System.Linq.WhereSelectEnumerableIterator2.MoveNext() +151
System.Linq.Enumerable.SingleOrDefault(IEnumerable1 source) +4222965 Ninject.Planning.Targets.Target1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Planning\Targets\Target.cs:179
Ninject.Planning.Targets.Target1.ResolveWithin(IContext parent) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Planning\Targets\Target.cs:147 Ninject.Activation.Strategies.PropertyInjectionStrategy.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Strategies\PropertyInjectionStrategy.cs:123 Ninject.Activation.Strategies.PropertyInjectionStrategy.Activate(IContext context, InstanceReference reference) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Strategies\PropertyInjectionStrategy.cs:76 Ninject.Activation.<>c__DisplayClass2.<Activate>b__0(IActivationStrategy s) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Pipeline.cs:58 Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable1 series, Action1 action) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerableOfT.cs:23 Ninject.Activation.Pipeline.Activate(IContext context, InstanceReference reference) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Pipeline.cs:58 Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Context.cs:173 Ninject.KernelBase.<Resolve>b__7(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\KernelBase.cs:375 System.Linq.<>c__DisplayClass123.b__11(TSource x) +32
System.Linq.WhereSelectEnumerableIterator2.MoveNext() +151 System.Linq.Enumerable.SingleOrDefault(IEnumerable1 source) +4222965
Ninject.Web.Mvc.NinjectDependencyResolver.GetService(Type serviceType) in c:\Projects\Ninject\Maintenance2.2\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs:56
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +51

[InvalidOperationException: An error occurred when trying to create a controller of type 'ReitanAppFeed.Controllers.NarvesenController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
System.Web.Mvc.<>c__DisplayClass6.b__2() +49
System.Web.Mvc.<>c__DisplayClassb1.<ProcessInApplicationTrust>b__a() +13 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969412
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

Module Ninject.Extensions.Logging.Log4Net.dll references an old version of log4net assembly

After installing your library using NuGet, and trying to instantiate a logger the application is unable to load the following assembly:
Name: log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821

Current Ninject.Extensions.Logging.Log4Net references an old log4net assembly (current assembly version for log4net is 1.2.11), thus the application fails at run time at instantiation.

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.