Kavita/API/Logging/LogLevelOptions.cs
Joe Milazzo c10acb1279
Security Event Logging & Bugfixes (#1882)
* Fixed bookmarking failing to convert to webp

* Brought the ag-swipe/ng-swipe code into Kavita due to being abandoned by developer and angular requirements.

* Fixed average reading time per week finally

* Cleaned up some extra decimals on time duration pipe

* Don't try to update index.html for base url on local. Fixed ag-swipe on prod mode.

* Updated a link on theme manager to point to the new github

* Range knobs should be primary color on firefox too

* Implemented the ability to get thumbnails of pages inside an archive or pdf.

* Updated packages and fixed opds-ps 1.2 issue

* Fixed lock file

* Allow Kavita's Swagger to hit instances with CORS

* Added IP/Request logging for Security Audits

* Linked up Summary tag from CBL into Kavita.

* Redid the migration so SecurityEvent now has UTC date as well.

* Split security logging to a separate file

* Update to new versions of checkout and setup

* Added a PR check on PR body to ensure that it doesn't contain any characters that break our discord hook.

* Updating action

* optimize regex in action

* Fixed an issue where fit to width would cause the actual height of the image to be shown for pagination bars, instead of rendered.

* Added some new code in GetPageFromFiles to ensure pages that exceed array map down to last file.

* Added comment about robots

* Fixed up unit tests for new ReaderService signature

* Kavita now cleans up empty reading lists at night

* Don't allow nightly cleanup to run if we are running media conversion tasks

* Fixed some bugs in typeahead, it should behave much more reliably.

* Fix an issue where emulate comic book wasn't extending to the bottom properly

* Added support for Series Chapter 001 Volume 001

* Refactor XFrameOptions="SameOrigins" out to allow users to override in appsettings.json.

* Added a rate limiter for some endpoints, but it doesn't seem to be triggering

---------

Co-authored-by: Robbie Davis <robbie@therobbiedavis.com>
2023-03-16 13:57:34 -07:00

120 lines
5.7 KiB
C#

using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Filters;
using Serilog.Formatting.Display;
namespace API.Logging;
/// <summary>
/// This class represents information for configuring Logging in the Application. Only a high log level is exposed and Kavita
/// controls the underlying log levels for different loggers in ASP.NET
/// </summary>
public static class LogLevelOptions
{
public const string LogFile = "config/logs/kavita.log";
public const string SecurityLogFile = "config/logs/security.log";
public const bool LogRollingEnabled = true;
/// <summary>
/// Controls the Logging Level of the Application
/// </summary>
private static readonly LoggingLevelSwitch LogLevelSwitch = new ();
/// <summary>
/// Controls Microsoft's Logging Level
/// </summary>
private static readonly LoggingLevelSwitch MicrosoftLogLevelSwitch = new (LogEventLevel.Error);
/// <summary>
/// Controls Microsoft.Hosting.Lifetime's Logging Level
/// </summary>
private static readonly LoggingLevelSwitch MicrosoftHostingLifetimeLogLevelSwitch = new (LogEventLevel.Error);
/// <summary>
/// Controls Hangfire's Logging Level
/// </summary>
private static readonly LoggingLevelSwitch HangfireLogLevelSwitch = new (LogEventLevel.Error);
/// <summary>
/// Controls Microsoft.AspNetCore.Hosting.Internal.WebHost's Logging Level
/// </summary>
private static readonly LoggingLevelSwitch AspNetCoreLogLevelSwitch = new (LogEventLevel.Error);
public static LoggerConfiguration CreateConfig(LoggerConfiguration configuration)
{
const string outputTemplate = "[Kavita] [{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {ThreadId}] [{Level}] {SourceContext} {Message:lj}{NewLine}{Exception}";
return configuration
.MinimumLevel
.ControlledBy(LogLevelSwitch)
.MinimumLevel.Override("Microsoft", MicrosoftLogLevelSwitch)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", MicrosoftHostingLifetimeLogLevelSwitch)
.MinimumLevel.Override("Hangfire", HangfireLogLevelSwitch)
.MinimumLevel.Override("Microsoft.AspNetCore.Hosting.Internal.WebHost", AspNetCoreLogLevelSwitch)
// Suppress noisy loggers that add no value
.MinimumLevel.Override("Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware", LogEventLevel.Error)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Error)
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.WriteTo.Console(new MessageTemplateTextFormatter(outputTemplate))
.WriteTo.File(LogFile,
shared: true,
rollingInterval: RollingInterval.Day,
outputTemplate: outputTemplate)
.Filter.ByIncludingOnly(ShouldIncludeLogStatement);
}
private static bool ShouldIncludeLogStatement(LogEvent e)
{
var isRequestLoggingMiddleware = e.Properties.ContainsKey("SourceContext") &&
e.Properties["SourceContext"].ToString().Replace("\"", string.Empty) ==
"Serilog.AspNetCore.RequestLoggingMiddleware";
// If Minimum log level is Information, swallow all Request Logging messages
if (isRequestLoggingMiddleware && LogLevelSwitch.MinimumLevel >= LogEventLevel.Information)
{
return false;
}
if (isRequestLoggingMiddleware)
{
if (e.Properties.ContainsKey("Path") && e.Properties["Path"].ToString().Replace("\"", string.Empty) == "/api/health") return false;
if (e.Properties.ContainsKey("Path") && e.Properties["Path"].ToString().Replace("\"", string.Empty) == "/hubs/messages") return false;
}
return true;
}
public static void SwitchLogLevel(string level)
{
switch (level)
{
case "Debug":
LogLevelSwitch.MinimumLevel = LogEventLevel.Debug;
MicrosoftLogLevelSwitch.MinimumLevel = LogEventLevel.Warning; // This is DB output information, Inf shows the SQL
MicrosoftHostingLifetimeLogLevelSwitch.MinimumLevel = LogEventLevel.Information;
AspNetCoreLogLevelSwitch.MinimumLevel = LogEventLevel.Warning;
break;
case "Information":
LogLevelSwitch.MinimumLevel = LogEventLevel.Information;
MicrosoftLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
MicrosoftHostingLifetimeLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
AspNetCoreLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
break;
case "Trace":
LogLevelSwitch.MinimumLevel = LogEventLevel.Verbose;
MicrosoftLogLevelSwitch.MinimumLevel = LogEventLevel.Information;
MicrosoftHostingLifetimeLogLevelSwitch.MinimumLevel = LogEventLevel.Debug;
AspNetCoreLogLevelSwitch.MinimumLevel = LogEventLevel.Information;
break;
case "Warning":
LogLevelSwitch.MinimumLevel = LogEventLevel.Warning;
MicrosoftLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
MicrosoftHostingLifetimeLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
AspNetCoreLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
break;
case "Critical":
LogLevelSwitch.MinimumLevel = LogEventLevel.Fatal;
MicrosoftLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
MicrosoftHostingLifetimeLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
AspNetCoreLogLevelSwitch.MinimumLevel = LogEventLevel.Error;
break;
}
}
}