Added logging to application.

This commit is contained in:
Daniel Wathen
2023-01-06 09:15:40 -07:00
parent 6de41bc8da
commit 9ee0b14ee9
6 changed files with 94 additions and 12 deletions

View File

@ -1,7 +1,14 @@
using ReportingServices.Shared.Repositories;
using Serilog;
LoggerConfiguration loggerConfiguration = new();
var builder = WebApplication.CreateBuilder(args);
Environment.SetEnvironmentVariable("workingDirectory", "C:/tmp/logging");
_ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, builder.Configuration);
_ = SerilogHostBuilderExtensions.UseSerilog(builder.Host);
Log.Logger = loggerConfiguration.CreateLogger();
Serilog.ILogger log = Log.ForContext<Program>();
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@ -24,5 +31,18 @@ app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
_ = app.Lifetime.ApplicationStopped.Register(Log.CloseAndFlush);
log.Information("Starting Web APIs");
app.Run();
try
{
app.Run();
}
catch (Exception ex)
{
log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}

View File

@ -11,6 +11,10 @@
<VSTestResultsDirectory>../.vscode/TestResults</VSTestResultsDirectory>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

View File

@ -5,5 +5,42 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Debug",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}"
}
},
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "%workingDirectory% - Log/log-.txt",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}",
"rollingInterval": "Hour"
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
],
"Properties": {
"Application": "Sample"
}
}
}