Ads

Web API 8 : Logging Information Or Error

ILogger comes under framework service.

ILogger is unique one , it does not require any registration under Dependency Injection. By default it is registered.

ILogger is a interface is used to write a log message of a given log level and create logging scopes. The interface itself only exposes some generic log methods  like LogInformation or LogError .


Lets see now how to log the info about api request with simple steps.

We will not going to create any new application, instead we use existing application. Lets download the source Web API Part 4 : Read the value from appsettings.json file

1. Open the source code in Visual Studio

2. Next Create Variable called _logger in LearningController

private readonly ILogger _logger;

3. Then we will do the constructor inject shown below

        public LearningController(AppDbContext context, 
            IOptions<MailInfo> mailInfo,
            ILogger<LearningController> logger
            )
        {
            _context = context;
            _mailInfo = mailInfo.Value;
            _logger = logger;
        }

4. Now, go to action method and add logic to capture the log information

        [HttpGet("send-mail")]
        public IActionResult SendMail()
        {
            _logger.LogInformation("Send Mail Service Started");
            if (_mailInfo.IsMailRequired)
            {
                _logger.LogInformation("Mail sent successfully");
                return Ok("mail sent to xyz@test.com from "+_mailInfo.MailFrom);
            }

            return Ok("Mail Failed");
        }

5. Lets run the application and hit the send-mail service

ILogger will log the information in the console.

6. Lets generate some error and log that

        [HttpGet("send-mail")]
        public IActionResult SendMail()
        {
            _logger.LogInformation("Send Mail Service Started");
            try
            {
                int result = 10, b = 30, c = 0;
                result = b / c;

                if (_mailInfo.IsMailRequired)
                {
                    _logger.LogInformation("Mail sent successfully");
                    return Ok("mail sent to xyz@test.com from " + _mailInfo.MailFrom);
                }

                return Ok("Mail Did Not Send");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message.ToString());
                return BadRequest();
            }            
        }

In above method we are dividing the value from zero, it will generate the error and goes to catch block.

Lets run the application again and hit the service send-mail

So finally!!! We have learnt that how to log the information in console. But its not good enough, we need to log the information or error in text file.

Come we will work on generating the log info to text file.

1. Lets install the dependency from NuGet package manager

  • Serilog.AspNetCore
  • Serilog.Sinks.File

2. We should write the following code in the Program.cs to configure the log target and specify the rolling interval and file size limit.

var logger = new LoggerConfiguration()
    .WriteTo.File(Path.Combine("C:\\Logs\\", "Test-Log-{Date}.txt"),
    rollingInterval: RollingInterval.Day, fileSizeLimitBytes: 100000)
    .CreateLogger();

builder.Host.UseSerilog(logger);

In above code we have selected the path C:\\Logs\\ folder, you can select any folder.

Then add below code before app.MapControllers();

app.UseSerilogRequestLogging();

We have done now, when you request SendMail method error will be logged into the text file.


Here is the text file


Thats it for this article.

You can download complete source code here Download Source Code

See you next article take care bye,

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !