Skip to content

Commit

Permalink
Simplified logging for dotnet core
Browse files Browse the repository at this point in the history
  • Loading branch information
binodmahto authored May 22, 2021
1 parent 9a68b23 commit d793072
Show file tree
Hide file tree
Showing 17 changed files with 903 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

</Project>
89 changes: 89 additions & 0 deletions DotNetCoreLogging/Demo.Logging.Model/ILogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using System;

namespace Demo.Logging.Model
{
/// <summary>
/// An interface for logging
/// </summary>
public interface ILogger
{
/// <summary>
/// Writes the given message if logging is turned on at the given level
/// </summary>
/// <param name="message"></param>
/// <param name="level"></param>
void Write(object message, LogLevels level)
{
Write(message, level, string.Empty);
}


/// <summary>
/// Writes the given message if logging is turned on at the given level
/// </summary>
/// <param name="message"></param>
/// <param name="level"></param>
/// <param name="categoryName"></param>
void Write(object message, LogLevels level, string categoryName);

/// <summary>
/// Writes the value returned by the message delegate, if logging is turned on at the given level for the given category
/// </summary>
/// <param name="msgDelegate"></param>
/// <param name="level"></param>
void Write(Func<object> msgDelegate, LogLevels level)
{
Write(msgDelegate, level, string.Empty);
}

/// <summary>
/// Writes the value returned by the message delegate, if logging is turned on at the given level for the given category
/// </summary>
/// <param name="msgDelegate"></param>
/// <param name="level"></param>
/// <param name="categoryName"></param>
void Write(Func<object> msgDelegate, LogLevels level , string categoryName);

/// <summary>
/// Tells if logging is enabled for the <see cref="LogLevels"/> or not.
/// </summary>
/// <param name="level"></param>
/// <returns></returns>
bool ShouldLog(LogLevels level);
}

/// <summary>
/// Valid Log levels for Prophet 21. More detailed logging may introduce significant performance costs.
/// </summary>
public enum LogLevels : byte
{
/// <summary>
/// No logging
/// </summary>
None,
/// <summary>
/// Error logs only
/// </summary>
Error,
/// <summary>
/// All warnings and errors
/// </summary>
Warning,
/// <summary>
/// All informational logging, warnings and errors
/// </summary>
Information,
/// <summary>
/// Detailed debug level logging, information, warning and errors
/// </summary>
Debug,
/// <summary>
/// Trace level logging, debug messages, informational messages, warnings and errors
/// </summary>
Trace,
/// <summary>
/// All logging including nested trace messages.
/// </summary>
All
}
}
22 changes: 22 additions & 0 deletions DotNetCoreLogging/Demo.Logging.Model/NullLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;

namespace Demo.Logging.Model
{
public class NullLogger : ILogger
{
public bool ShouldLog(LogLevels level)
{
return false;
}

public void Write(object message, LogLevels level, string categoryName)
{
//Do Nothing
}

public void Write(Func<object> msgDelegate, LogLevels level, string categoryName)
{
//Do Nothing
}
}
}
18 changes: 18 additions & 0 deletions DotNetCoreLogging/Demo.Logging.Serilog/Demo.Logging.Serilog.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Demo.Logging.Model\Demo.Logging.Model.csproj" />
</ItemGroup>

</Project>
132 changes: 132 additions & 0 deletions DotNetCoreLogging/Demo.Logging.Serilog/SerilogFileLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
using System;
using System.IO;
using Serilog;
using Microsoft.Extensions.Configuration;
using Serilog.Events;
using Demo.Logging.Model;
using Serilog.Formatting.Compact;

namespace Demo.Logging.Serilog
{
public class SerilogFileLogger : Model.ILogger
{
/// <summary>
/// Default constructor reading settings from config (appsettings.json) file.
/// </summary>
public SerilogFileLogger()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}

/// <summary>
/// constructor
/// </summary>
/// <param name="logFilePath">Fully qualified log file path i.e. c:\temp\log.json</param>
/// <param name="level"><see cref="LogLevels"/> for the log</param>
/// <param name="fileSizeLimitBytes">Max log file size</param>
public SerilogFileLogger(string logFilePath, LogLevels level, long? fileSizeLimitBytes = null)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.WriteTo.File(new CompactJsonFormatter(), logFilePath, fileSizeLimitBytes: fileSizeLimitBytes ?? 1073741824,
rollOnFileSizeLimit: true,
shared: true,
flushToDiskInterval: TimeSpan.FromSeconds(1))
.CreateLogger();
}

public void Write(object message, LogLevels level)
{
WriteLog(message, level);
}

public void Write(object message, LogLevels level, string category)
{
WriteLog(message, level, category);
}

public void Write(Func<object> msgDelegate, LogLevels level, string category)
{
WriteLog(msgDelegate.Invoke(), level, category);
}

public bool ShouldLog(LogLevels level)
{
return Log.IsEnabled(ToLogEventLevel(level));
}

private void WriteLog(object message, LogLevels level, string category = "")
{
var ex = message as Exception;
var messageTemplate = $"{message}";
if (!String.IsNullOrEmpty(category))
messageTemplate = $"{category}=>{(ex == null ? ex.Message : message)}";

switch (level)
{
case LogLevels.Error:
if (ex != null)
Log.Error(ex, messageTemplate);
else
Log.Error(messageTemplate);
break;
case LogLevels.Warning:
if (ex != null)
Log.Warning(ex, messageTemplate);
else
Log.Warning(messageTemplate);
break;
case LogLevels.Information:
if (ex != null)
Log.Information(ex, messageTemplate);
else
Log.Information(messageTemplate);
break;
case LogLevels.Debug:
case LogLevels.Trace:
case LogLevels.All:
if (ex != null)
Log.Verbose(ex, messageTemplate);
else
Log.Verbose(messageTemplate);
break;
default:
throw new ArgumentOutOfRangeException(nameof(level), level, null);
}


}

private LogEventLevel ToLogEventLevel(LogLevels level)
{
switch (level)
{
case LogLevels.Error:
return LogEventLevel.Error;
case LogLevels.Warning:
return LogEventLevel.Warning;
case LogLevels.Information:
return LogEventLevel.Information;
case LogLevels.Debug:
case LogLevels.Trace:
case LogLevels.All:
return LogEventLevel.Verbose;
default:
throw new ArgumentOutOfRangeException(nameof(level), level, null);
}
}
}
}
12 changes: 12 additions & 0 deletions DotNetCoreLogging/Demo.Logging/Demo.Logging.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Demo.Logging.Model\Demo.Logging.Model.csproj" />
<ProjectReference Include="..\Demo.Logging.Serilog\Demo.Logging.Serilog.csproj" />
</ItemGroup>

</Project>
Loading

0 comments on commit d793072

Please sign in to comment.