Azure App Service and Diagnostic logging using asp.net core

I have used the same example from the previous article to introduce diagnostic logging in Azure. I would recommend you to go through below article but not mandatory. 

Azure provides built-in support for diagnostic logs for the Azure App Service. We’ll also learn how to enable the diagnostic logs and to check using the ftp server location. 

Overview

Deploying apps to Azure app service is very easy. But imagine, occasionally there might be instances where you end up with error during app startup; moreover, it’s hard to debug as the app is not started yet. In order to overcome these problem, Microsoft has come up with great tool called Diagnostic logs to identify the cause of the issue. 

Code Changes

Firstly, we need to add Microsoft.Extension.Logging.AzureAppService nuget package. 

Next Step is to configure logging in the host builder methods of the program file. 

public static IHostBuilder CreateHostBuilder(string[] args) =>

            Host.CreateDefaultBuilder(args)

                .ConfigureWebHostDefaults(webBuilder =>

                {

                    webBuilder.UseStartup<Startup>();

                }).ConfigureLogging(options =>

                {

                    options.ClearProviders();

                    options.AddConsole();

                    options.AddAzureWebAppDiagnostics();

                });

    }

options.AddAzureWebAppDiagnostics method is used to add the diagnostic logs in Azure app service. 

Next, we need to configure the file logger option in the startup class

public void ConfigureServices(IServiceCollection services)

        {

            services.AddControllers();

            services.Configure<AzureFileLoggerOptions>(options =>

            {

                 options.FileName = “azure-diagnostics-“;

                options.FileSizeLimit = 50 * 1024;

                options.RetainedFileCountLimit = 5;

            });

            services.AddDbContext<EmployeeContext>(options =>

            {

                options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));

            });

            services.AddMvc().AddFluentValidation(x => x.RegisterValidatorsFromAssemblyContaining<Startup>());

        }

Here, we are configuring only for the file but you can configure for the blog storage as well using below code in configureServices method

Services.Configure<AzureBlobLoggerOptions>(options =>

                {

                    options.BlobName = “log.txt”;

                })

Next, I have modified the EmployeeController to support logging

Route(“api/[controller]”)]

    public class EmployeeController : ControllerBase

    {

        private readonly EmployeeContext _employeeContext;

        private readonly ILogger<EmployeeController> _logger;

        public EmployeeController(EmployeeContext employeeContext,ILogger<EmployeeController> logger)

        {

            _employeeContext = employeeContext;

            _logger = logger;

        }

        // GET: api/values

        [HttpGet]

        public IEnumerable<Employee> GetAllEmployees()

        {

            _logger.LogInformation(“Get all employee has been called”);

            return _employeeContext.Employees;

        }

        // GET api/values/5

        [HttpGet(“{id}”)]

        public Employee GetEmployee(int id)

        {

            return _employeeContext.Employees.FirstOrDefault(x => x.Id == id);

        }

        // POST api/values

        [HttpPost]

        public IActionResult InsertEmployee([FromBody]Employee employee)

        {

            _logger.LogInformation(“Post Employee method has been called”);

            _logger.LogInformation($”model state is {ModelState.IsValid}”);

            _logger.LogInformation(JsonSerializer.Serialize(employee));

            if (ModelState.IsValid)

            {

                _employeeContext.Employees.Add(employee);

                _employeeContext.SaveChanges();

                return Ok();

            }

            return ValidationProblem();

        }

        // PUT api/values/5

        [HttpPut(“{id}”)]

        public IActionResult UpdateEmployee([FromBody]Employee employee)

        {

            _logger.LogInformation(“Update Employee method has been called”);

            _logger.LogInformation($”model state is {ModelState.IsValid}”);

            _logger.LogInformation(JsonSerializer.Serialize(employee));

            if (ModelState.IsValid)

            {

                _employeeContext.Employees.Update(employee);

                _employeeContext.SaveChanges();

                return Ok();

            }

            return ValidationProblem();

        }

        // DELETE api/values/5

        [HttpDelete(“{id}”)]

        public IActionResult DeleteEmployee(int id)

        {

            _logger.LogInformation(“Update Employee method has been called”);

            _logger.LogInformation($”model state is {ModelState.IsValid}”);

            _logger.LogInformation($”id for delete employee is {id}”);

            if (id == 0)

            {

                _logger.LogError(“Id cannot 0”);

                return BadRequest(“Id cannot be null”);

            }

            var employee = _employeeContext.Employees.FirstOrDefault(x => x.Id == id);

            if (employee != null)

            {

                _logger.LogInformation(JsonSerializer.Serialize(employee));

                _employeeContext.Employees.Remove(employee);

                _employeeContext.SaveChanges();

            }

            return Ok();

        }

    }

Note: In this article, we’ll be looking for file based option.

Finally, publish the application to Azure. 

Enabling Diagnostic Logs

Diagnostic logs can be easily enabled using Azure portal user interface. Navigate to app server and click on App server logs

Verify whether you are able to connect to Log stream. Once the Log Stream is successful, we are good to go. 

Now, time to run your application. In my case, url will be like this 

https://XXX.azurewebsites.net/api/employee/

Download Diagnostic log File

You can easily download the log file by using the FTP/FTPS url provided in the App Server logs. You can get the user name and password of the FTP in the “Get Publish Profile” in the overview tab of the app service. Please go through the below article to see the details/url to navigate to the respective log files

https://docs.microsoft.com/en-us/azure/app-service/troubleshoot-diagnostic-logs

I hope you like the article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s