Reputation: 39
My backend service is an ASP.NET Core 6 Web API. I am using table storage to maintain API logs, I have a logging middleware which typically stores the log in Azure table storage when the API request is complete.
And this is the implementation
TableClient client = GetTableClient(connectionString, tableName);
if (createTableIfNotExists())
await client.CreateIfNotExistsAsync();
await client.AddEntityAsync(tableEntityDto);
In short, this will use the connection string to check whether the table already exists, or need to create one. Then it will insert the log obj in the table storage.
This is perfectly working as expected in my local. But when I hosted my API in Azure Web App, I was unable to see the logs generated.
I even tried to create a table name based on my pattern, yet I couldn't see the log object. Am I missing something? Or do you have any suggestion on how to tackle this issue?
Upvotes: 0
Views: 89
Reputation: 12789
You could try this below code:
LoggingMiddleware.cs:
using Azure;
using Azure.Data.Tables;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace azurelogging.Middleware
{
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly string _connectionString = "YourConnectionString";
private readonly string _tableName = "ApiLogs";
public LoggingMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_connectionString = configuration.GetConnectionString("AzureTableStorage");
}
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
await _next(context);
stopwatch.Stop();
var log = new LogEntity
{
PartitionKey = "ApiLog",
RowKey = Guid.NewGuid().ToString(),
HttpMethod = context.Request.Method,
Path = context.Request.Path,
ResponseStatusCode = context.Response.StatusCode,
ProcessingTime = stopwatch.ElapsedMilliseconds
};
await LogToTableStorageAsync(log);
}
private async Task LogToTableStorageAsync(LogEntity log)
{
try
{
TableClient client = new TableClient(_connectionString, _tableName);
await client.CreateIfNotExistsAsync();
await client.AddEntityAsync(log);
}
catch (Exception ex)
{
// Log exception to console or another logging mechanism
Console.WriteLine($"Exception occurred: {ex.Message}");
}
}
}
public class LogEntity : ITableEntity
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string HttpMethod { get; set; }
public string Path { get; set; }
public int ResponseStatusCode { get; set; }
public long ProcessingTime { get; set; }
public DateTimeOffset? Timestamp { get; set; }
public ETag ETag { get; set; }
}
}
MiddlewareExtensions.cs:
using azurelogging.Middleware;
using Microsoft.AspNetCore.Builder;
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LoggingMiddleware>();
}
}
Program.cs:
app.UseLoggingMiddleware();
Make sure the connection string is correctly set in the appsetting file.
Ensure that there are no environment-specific differences (e.g., different versions of libraries or SDKs) between your local development environment and the Azure Web App.check web app logs if is there any error. if it still does not work enable logging:
try
{
TableClient client = GetTableClient(connectionString, tableName);
Console.WriteLine("TableClient created successfully.");
if (createTableIfNotExists())
{
Console.WriteLine("Creating table if not exists.");
await client.CreateIfNotExistsAsync();
Console.WriteLine("Table created or already exists.");
}
await client.AddEntityAsync(tableEntityDto);
Console.WriteLine("Entity added successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Exception occurred: {ex.Message}");
// Consider logging the stack trace and other details as needed
}
Upvotes: 0