Skip to content

Commit

Permalink
feat(logger): updated to serilog
Browse files Browse the repository at this point in the history
  • Loading branch information
roehlerw committed Sep 23, 2020
1 parent 6f9cb80 commit 4365376
Show file tree
Hide file tree
Showing 4 changed files with 154 additions and 81 deletions.
79 changes: 45 additions & 34 deletions PluginMySQL/Helper/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.IO;
using System.Threading;
using Grpc.Core;
using Serilog;

namespace PluginMySQL.Helper
{
Expand All @@ -17,48 +18,53 @@ public enum LogLevel
}

private static string _logPrefix = "";
private static string _path = @"plugin-mysql-log.txt";
private static string _fileName = @"plugin-mysql-log.txt";
private static LogLevel _level = LogLevel.Info;
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();


/// <summary>
/// Writes a log message with time stamp to a file
/// Initializes the logger
/// </summary>
/// <param name="message"></param>
private static void Log(string message)
public static void Init()
{
// Set Status to Locked
_readWriteLock.EnterWriteLock();
try
{
// ensure log directory exists
Directory.CreateDirectory("logs");

// Append text to the file
var filePath = $"logs/{_logPrefix}{_path}";
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine($"{DateTime.Now} {message}");
sw.Close();
}
}
finally
{
// Release lock
_readWriteLock.ExitWriteLock();
}
// ensure log directory exists
Directory.CreateDirectory("logs");

// setup serilog
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.WriteTo.Async(
sinkConfig =>
{
sinkConfig.File(
$"logs/{_fileName}",
rollingInterval: RollingInterval.Day,
shared: true,
rollOnFileSizeLimit: true
);
sinkConfig.Console();
})
.CreateLogger();
}

/// <summary>
/// Closes the logger and flushes any pending messages in the buffer
/// </summary>
public static void CloseAndFlush()
{
Log.CloseAndFlush();
}

/// <summary>
/// Deletes log file if it is older than 7 days
/// </summary>
public static void Clean()
{
if (File.Exists(_path))
if (File.Exists(_fileName))
{
if ((File.GetCreationTime(_path) - DateTime.Now).TotalDays > 7)
if ((File.GetCreationTime(_fileName) - DateTime.Now).TotalDays > 7)
{
File.Delete(_path);
File.Delete(_fileName);
}
}
}
Expand All @@ -76,7 +82,8 @@ public static void Verbose(string message)

GrpcEnvironment.Logger.Debug(message);

Log(message);
// WriteLog(message);
Log.Verbose(message);
}

/// <summary>
Expand All @@ -92,7 +99,8 @@ public static void Debug(string message)

GrpcEnvironment.Logger.Debug(message);

Log(message);
// WriteLog(message);
Log.Debug(message);
}
/// <summary>
/// Logging method for Info messages
Expand All @@ -107,7 +115,8 @@ public static void Info(string message)

GrpcEnvironment.Logger.Info(message);

Log(message);
// WriteLog(message);
Log.Information(message);
}

/// <summary>
Expand All @@ -124,7 +133,8 @@ public static void Error(Exception exception, string message)

GrpcEnvironment.Logger.Error(exception, message);

Log(message);
// WriteLog(message);
Log.Error(exception, message);
}

/// <summary>
Expand All @@ -143,7 +153,8 @@ public static void Error(Exception exception, string message, ServerCallContext
GrpcEnvironment.Logger.Error(exception, message);
context.Status = new Status(StatusCode.Unknown, message);

Log(message);
// WriteLog(message);
Log.Error(exception, message);
}

/// <summary>
Expand Down
4 changes: 4 additions & 0 deletions PluginMySQL/PluginMySQL.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
<PackageReference Include="MySqlConnector" Version="0.61.0" />
<PackageReference Include="Naveego.Sdk" Version="1.1.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
<PackageReference Include="System.Linq.Async" Version="4.0.0" />
</ItemGroup>

Expand Down
16 changes: 10 additions & 6 deletions PluginMySQL/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Grpc.Core;
using Naveego.Sdk.Plugins;
using PluginMySQL.Helper;
using Serilog;

namespace PluginMySQL
{
Expand All @@ -12,15 +13,16 @@ static void Main(string[] args)
{
try
{
// setup logger
Logger.Init();

// Add final chance exception handler
AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
{
Logger.Error(null, $"died: {eventArgs.ExceptionObject}");
Logger.CloseAndFlush();
};

// clean old logs on start up
Logger.Clean();


// create new server and start it
Server server = new Server
{
Expand All @@ -41,15 +43,17 @@ static void Main(string[] args)
Console.ReadLine();

Logger.Info("Plugin exiting...");
Logger.CloseAndFlush();

// shutdown server
server.ShutdownAsync().Wait();
}
catch (Exception e)
{
Logger.Error(e, e.Message);;
Logger.Error(e, e.Message);
Logger.CloseAndFlush();
throw;
}
}
}
}
}
Loading

0 comments on commit 4365376

Please sign in to comment.