log4net - Getting the CategoryName from a ILogger - Stack Overflow

admin2025-04-15  0

We are working on migrating from log4net to the Microsoft.Extensions.Logging library and I'm implementing an ILogger to write to our existing log table. One of the things we log from log4net is the "Logger" which is the class using the logger. So we have (with log4net) ILog Logger = LogManager.GetLogger(typeof(MyLibrary.MyClass))

and for the logger vale inserted into the DB it will be MyLibrary.MyClass.

I'm trying to do the same in the MS Logging extensions, which seems to call it 'CategoryName'. So we use ILogger<MyLibrary.MyClass> in MyClass so it an log. (ILogger<TCategoryName> in the documenation).

In my public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) implementation though I don't see anyway to actually get the TCategoryName.

Is there anyway to actually get to the category name, and if so how?

I tried looking at TState but it is always Microsoft.Extensions.Logging.FormattedLogValues which is a list of KeyValuePair<string, object> or Microsoft.Extensions.Logging.LoggerMessage+LogValues``1 which doesn't seem to contain the data I'm looking for.

We are working on migrating from log4net to the Microsoft.Extensions.Logging library and I'm implementing an ILogger to write to our existing log table. One of the things we log from log4net is the "Logger" which is the class using the logger. So we have (with log4net) ILog Logger = LogManager.GetLogger(typeof(MyLibrary.MyClass))

and for the logger vale inserted into the DB it will be MyLibrary.MyClass.

I'm trying to do the same in the MS Logging extensions, which seems to call it 'CategoryName'. So we use ILogger<MyLibrary.MyClass> in MyClass so it an log. (ILogger<TCategoryName> in the documenation).

In my public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) implementation though I don't see anyway to actually get the TCategoryName.

Is there anyway to actually get to the category name, and if so how?

I tried looking at TState but it is always Microsoft.Extensions.Logging.FormattedLogValues which is a list of KeyValuePair<string, object> or Microsoft.Extensions.Logging.LoggerMessage+LogValues``1 which doesn't seem to contain the data I'm looking for.

Share Improve this question asked Feb 4 at 12:46 ksjaksja 1
Add a comment  | 

1 Answer 1

Reset to default 0

I found out how to do this, it turns out its pretty simple I just didn't think to look outside the ILogger code.

In your ILoggerProvider the ILogger CreateLogger(string categoryName) has the category name from ILogger<TCategoryName>. Just need to pass that to the constructor of your ILogger.

e.g. public ILogger CreateLogger(string categoryName) => new DbLogger(this, categoryName, TimeProvider.System);

转载请注明原文地址:http://www.anycun.com/QandA/1744718616a86661.html