michasaucer
michasaucer

Reputation: 5228

Show log object in console from ILogger<Class> log critical

im using ILogger interface to log information about my app into console.

Im logging unathorized acces to my app:

private readonly RequestDelegate _next;
private readonly ILogger<SomeClass> _logger;

public SomeClass(RequestDelegate next, ILogger<SomeClass> logger)
{
      _next = next;
      _logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

// some methods there

_logger.LogCritical(
      $"{DateTime.UtcNow} - Unauthorized Access",
      new 
      { 
          token = jwt, 
          // other stuff
      });

But in console, i get only message;

crit: namespace.to.my.app.SomeClass[0]
      24.07.2020 07:36:37 - Unauthorized Access

How to display that anonymous object that i created into console?

Upvotes: 2

Views: 856

Answers (1)

Sean
Sean

Reputation: 62472

ILogger is a semantic logger so you need a token in the log string to represent what you are logging. Try this:

_logger.LogCritical
(
  "{Time} - Unauthorized Access. Details {Details}",
  DateTime.UtcNow,
  new 
  { 
    token = jwt, 
    // other stuff
});

Note that string interpolation doesn't play well with sematic logging so I've moved the DateTime.UtcNow expression out and given it a token in the log string.

Upvotes: 2

Related Questions