DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Trending

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • The End of “Good Enough Agile”
  • Event Driven Architecture (EDA) - Optimizer or Complicator
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Add Custom Logging in ASP.NET Core

How to Add Custom Logging in ASP.NET Core

If you want to create a custom logging system for your ASP.NET Core application, continue reading to get the advice of an expert.

By 
Jurgen Gutsch user avatar
Jurgen Gutsch
·
May. 08, 17 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
26.4K Views

Join the DZone community and get the full member experience.

Join For Free

asp.net core is pretty flexible, customizable, and extendable. you are able to change almost everything. even the logging. if you don't like the built-in logging, you are able to plug in your own logger or an existing logger like log4net, nlog, elmah. in this post, i'm going to show you how to add a custom logger.

the logger i show you just writes out to the console, but just for one single log level. the feature is to configure different font colors per loglevel. so this logger is called coloredconsolelogger .

general

to add a custom logger, you need to add an iloggerprovider to the iloggerfactory , that is provided in the method configure in the startup.cs :

loggerfactory.addprovider(new customloggerprovider(new customloggerconfiguration())); 

the iloggerprovider creates one or more ilogger which are used by the framework to log the information.

the configuration

the idea is to create different colored console entries per log level and event id. to configure this we need a configuration type like this:

public class coloredconsoleloggerconfiguration
{
  public loglevel loglevel { get; set; } = loglevel.warning;
  public int eventid { get; set; } = 0;
  public consolecolor color { get; set; } = consolecolor.yellow;
}

this sets the default level to warning and the color to yellow . if the eventid is set to 0, we will log all events.

the logger

the logger gets a name and the configuration passed in via the constructor. the name is the category name, which usually is the logging source, eg. the type where the logger is created in:

public class coloredconsolelogger : ilogger
{
  private readonly string _name;
  private readonly coloredconsoleloggerconfiguration _config;

  public coloredconsolelogger(string name, coloredconsoleloggerconfiguration config)
  {
    _name = name;
    _config = config;
  }

  public idisposable beginscope<tstate>(tstate state)
  {
    return null;
  }

  public bool isenabled(loglevel loglevel)
  {
    return loglevel == _config.loglevel;
  }

  public void log<tstate>(loglevel loglevel, eventid eventid, tstate state, exception exception, func<tstate, exception, string> formatter)
  {
    if (!isenabled(loglevel))
    {
      return;
    }

    if (_config.eventid == 0 || _config.eventid == eventid.id)
    {
      var color = console.foregroundcolor;
      console.foregroundcolor = _config.color;
      console.writeline($"{loglevel.tostring()} - {eventid.id} - {_name} - {formatter(state, exception)}");
      console.foregroundcolor = color;
    }
  }
}

we are going to create a logger instance per category name with the provider.

the loggerprovider

the loggerprovider is the guy who creates the logger instances. maybe it is not needed to create a logger instance per category, but this makes sense for some loggers, like nlog or log4net. doing this you are also able to choose different logging output targets per category if needed:

 public class coloredconsoleloggerprovider : iloggerprovider
  {
    private readonly coloredconsoleloggerconfiguration _config;
    private readonly concurrentdictionary<string, coloredconsolelogger> _loggers = new concurrentdictionary<string, coloredconsolelogger>();

    public coloredconsoleloggerprovider(coloredconsoleloggerconfiguration config)
    {
      _config = config;
    }

    public ilogger createlogger(string categoryname)
    {
      return _loggers.getoradd(categoryname, name => new coloredconsolelogger(name, _config));
    }

    public void dispose()
    {
      _loggers.clear();
    }
  }

there's no magic here. the method createlogger creates a single instance of the coloredconsolelogger per category name and stores it in the dictionary.

usage

now we are able to use the logger in the startup.cs

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
{
  loggerfactory.addconsole(configuration.getsection("logging"));
  loggerfactory.adddebug();
  // here is our customlogger
  loggerfactory.addprovider(new coloredconsoleloggerprovider(new coloredconsoleloggerconfiguration
  {
    loglevel = loglevel.information,
    color = consolecolor.blue
  }));
  loggerfactory.addprovider(new coloredconsoleloggerprovider(new coloredconsoleloggerconfiguration
  {
    loglevel = loglevel.debug,
    color = consolecolor.gray
  }));

but this doesn't really look nice from my point of view. i want to use something like this:

loggerfactory.addcoloredconsolelogger(c =>
{
  c.loglevel = loglevel.information;
  c.color = consolecolor.blue;
});
loggerfactory.addcoloredconsolelogger(c =>
{
  c.loglevel = loglevel.debug;
 c.color = consolecolor.gray;
});

this means we need to write at least one extension method for the iloggerfactory :

public static class coloredconsoleloggerextensions
{
  public static iloggerfactory addcoloredconsolelogger(this iloggerfactory loggerfactory, coloredconsoleloggerconfiguration config)
  {
    loggerfactory.addprovider(new coloredconsoleloggerprovider(config));
    return loggerfactory;
  }
  public static iloggerfactory addcoloredconsolelogger(this iloggerfactory loggerfactory)
  {
    var config = new coloredconsoleloggerconfiguration();
    return loggerfactory.addcoloredconsolelogger(config);
  }
  public static iloggerfactory addcoloredconsolelogger(this iloggerfactory loggerfactory, action<coloredconsoleloggerconfiguration> configure)
  {
    var config = new coloredconsoleloggerconfiguration();
    configure(config);
    return loggerfactory.addcoloredconsolelogger(config);
  }
}

with this extension method, we are able to pass in an already defined configuration object, we can use the default configuration or use the configure action as shown in the previous example:

loggerfactory.addcoloredconsolelogger();
loggerfactory.addcoloredconsolelogger(new coloredconsoleloggerconfiguration
{
  loglevel = loglevel.debug,
  color = consolecolor.gray
});
loggerfactory.addcoloredconsolelogger(c =>
{
  c.loglevel = loglevel.information;
  c.color = consolecolor.blue;
});

conclusion

this is how the output of that nonsense logger looks:

now it's up to you to create a logger that writes the entries to a database, log file or whatever or just add an existing logger to your asp.net core application.

ASP.NET Core ASP.NET

Published at DZone with permission of Jurgen Gutsch. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!