3

So I'm trying to setup ILogger with Dependency Injection and I'm having some trouble.

In my startup.cs file I have something that looks like this:

        builder.Services.AddLogging();

I then try to feed that logger to my own class (which acts like a wrapper around the ILogger library)

    builder.Services.AddSingleton<LoggingWrapper>(s =>
    {
        return new LoggingWrapper(
            s.GetService<ILoggerFactory>());
    });

So in my Azure function, LoggingWrapper gets injected inside, but it doesn't log anything. The normal ILogger that comes with each function still works, but I'm wondering as to why my wrapper isn't logging anything.

Logging Wrapper is a class that takes the ILogger methods and uses it to create it's own logging methods. For example loggingWrapper.logInformation("string") is a method that would wrap around `ILogger.

I inject this into my other classes like this: s.GetService<ILoggerFactory>()

Thanks in advance for all the help!

1
  • Show where the logger is injected and used. Commented Aug 13, 2020 at 23:13

2 Answers 2

14

I faced the same problem - you need to setup/allow logging from other sources:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "YourNamespace": "Information"
    }
  }
}

More information here:

Sign up to request clarification or add additional context in comments.

1 Comment

Information: This is the host.json file
1

Do you mean to inject an ILogger?

//NOT...                     <LoggingWrapper>
builder.Services.AddSingleton<ILogger>(s =>
{
    return new LoggingWrapper(
        s.GetService<ILoggerFactory>());
});

2 Comments

So LoggerWrapper is a class that hides all the ILogger methods and uses them to create it's own log methods. When I inject it into a class, I do so like s.GetService<IAccountUpdaterLogger>(), but that doesn't seem to work
@idude s.GetService() is "service location", not "dependency injection". They're similar patterns, but the only thing that will be injected by a given framework is whatever is accepted in the constructor (ILogger in this case). Try having LoggingWrapper implement ILogger, then follow a "decorator" pattern, accepting an internal ILogger when you instantiate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.