ILogger

ILogger represents the principal component used to write log messages.

public void Foo()
{
    ILogger logger = Logger.Factory.Get();

    logger.Debug("Foo started");
}

Contents

Log levels

ILogger exposes all the log levels used by .NET Framework.

public void Foo()
{
    ILogger logger = Logger.Factory.Get();

    // Trace
    logger.logger.Trace("Database connection opened");

    // Debug
    logger.Debug("Two factor authentication started");

    // Information
    logger.Info($"Recover password email sent for email {emailAddress}");

    // Warning
    logger.Warn($"Cache entry for {key} was not found");

    // Error
    logger.Error($"User with Id = {userId} was not found");

    // Critical
    logger.Critical("There is not enough space on the disk. Save failed.");
}

Log arguments

Each log method accepts multiple arguments overloads.

public void Foo()
{
    ILogger logger = Logger.Factory.Get();

    // string
    logger.Info("String value");

    // object
    logger.Warn(new { Id = 10, Price = 100.4M, Name = "Product 1" });

    // System.Exception
    logger.Error(new FileNotFoundException());

    // Args
    logger.Dubug(new Args("Error creating product", 30, new FileNotFoundException()));
}

Logging files

ILogger exposes methods which allows developers to save raw data as files.

When a file is logged, a temporary copy is created. The original file is not altered or referenced.

The temporary files are automaticaly discarded at the end of the Http Request.

public void Foo()
{
    ILogger logger = Logger.Factory.Get();

    byte[] archive = File.ReadAllBytes(@"C:\Files\bootstrap.zip");
    logger.LogAsFile(archive, "Bootstrap.zip");

    string xml = File.ReadAllText(@"C:\Files\cd_catalog.xml");
    logger.LogAsFile(xml, "Catalog.xml");

    string path = @"C:\Files\Invoice-16-11-2017.pdf";
    logger.LogFile(path, "Invoice.pdf");
}

Acquiring ILogger instance

An ILogger instance is created and shared automatically per each Http Request.

To retreive the ILogger, use Logger.Factory.Get() factory method.

Calling this method multiple times will return the same ILogger instance per Http Request.

public void Foo()
{
    ILogger logger = Logger.Factory.Get();
}

ILogger can be integrated using dependency injection, and, in most of the situations, you won't need to create the ILogger instance manually.


Related references