Skip to content

Instantly share code, notes, and snippets.

@framinosona framinosona/Logging.cs
Last active Feb 25, 2019

Embed
What would you like to do?
NLog sample
using System;
using System.Runtime.CompilerServices;
using System.Text;
using NLog;
namespace LoggingDemo.Helpers
{
public static class Logging
{
private static Logger _logger; //NLog logger
public static void Initialize()
{
_logger = LogManager.GetLogger("Default") ?? LogManager.GetCurrentClassLogger();
var config = new NLog.Config.LoggingConfiguration();
var logFile = new NLog.Targets.FileTarget()
{
FileName = "nlog.log",
Name = "logfile",
Layout = "${level:upperCase=true}:${message}${exception:format=ToString}"
};
var logConsole = new NLog.Targets.ColoredConsoleTarget()
{
Name = "logconsole",
Layout = "${level:upperCase=true}:${message}"
};
config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, logConsole));
config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logFile));
LogManager.Configuration = config;
typeof(Logging).Trace($"Logging started. Log file: {logFile.FileName}");
}
public static void Trace<T>(
this T caller,
string message = "",
Exception ex = null,
[CallerMemberName] string callerFunction = "")
{
if (!_logger.IsTraceEnabled) return;
var line = BuildLogLine(caller, message, callerFunction);
_logger.Trace(ex, line);
}
public static void Info<T>(
this T caller,
string message,
Exception ex = null,
[CallerMemberName] string callerFunction = "")
{
if (!_logger.IsInfoEnabled) return;
var line = BuildLogLine(caller, message, callerFunction);
_logger.Info(ex, line);
}
public static void Warn<T>(
this T caller,
string message,
Exception ex = null,
[CallerMemberName] string callerFunction = "")
{
if (!_logger.IsWarnEnabled) return;
var line = BuildLogLine(caller, message, callerFunction);
_logger.Warn(ex, line);
}
public static void Warn<T>(
this T caller,
Exception ex,
[CallerMemberName] string callerFunction = "")
{
if (!_logger.IsWarnEnabled) return;
var line = BuildLogLine(caller, ex.Message, callerFunction);
_logger.Warn(ex, line);
}
public static void Error<T>(
this T caller,
Exception ex,
[CallerMemberName] string callerFunction = "")
{
if (!_logger.IsErrorEnabled) return;
var line = BuildLogLine(caller, ex.Message, callerFunction);
_logger.Error(ex, line);
}
public static void Error<T>(
this T caller,
string message,
Exception ex,
[CallerMemberName] string callerFunction = "")
{
if (!_logger.IsErrorEnabled) return;
var line = BuildLogLine(caller, message, callerFunction);
_logger.Error(ex, line);
}
private static string BuildLogLine<T>(
T caller,
string message = "",
string callerFunction = "")
{
StringBuilder sb = new StringBuilder();
var type = caller as Type;
var callerName = (type != null ? type : caller.GetType()).Name;
sb.Append($@" {callerName}");
if (!String.IsNullOrWhiteSpace(callerFunction))
sb.Append($@".{callerFunction}");
if (!String.IsNullOrWhiteSpace(message))
sb.Append($@": {message}");
return sb.ToString();
}
}
}
using System;
using LoggingDemo.Helpers;
namespace LoggingDemo
{
public class MyClass
{
public void MyMethod()
{
// this.Info, this.Trace and this.Warn can be used at any point in the code.
this.Info("For your information, this is happening right now");
this.Trace("Here is some raw data I received at this point : { 'name': 'yolo' }");
this.Warn("I don't like this, something weird happened ...");
// The message string is optional.
// This is useful to track a specific point of the code without using breakpoints.
this.Trace();
}
public void ThrowException()
{
throw new Exception("Nope");
}
}
}
using LoggingDemo.Helpers;
namespace LoggingDemo
{
public static class MyStaticClass
{
public static void MyStaticFunction()
{
// Since the keyword "this" is not available in a static context we need to use a ruse.
// Types are objects, a static class may not have an instance but it has a type !
typeof(MyStaticClass).Info("For your information, this is happening right now");
typeof(MyStaticClass).Trace("Here is some raw data I received at this point : { 'name': 'yolo' }");
typeof(MyStaticClass).Warn("I don't like this, something weird happened ...");
}
}
}
using System;
using LoggingDemo.Helpers;
namespace LoggingDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
LoggingHelper.Initialize();
// Info, Trace, Warn :
var myObject = new MyClass();
myObject.MyMethod();
// Errors and exceptions:
try
{
myObject.ThrowException();
}
catch (Exception ex)
{
// this.Warn can take an exception parameter too.
// This is useful for logging predictable/expected exceptions.
typeof(Program).Warn("I knew something had happened !", ex);
// this.Error always needs an exception.
// This forces all developers to handle errors with exceptions.
typeof(Program).Error("Something definitely broke there", ex);
}
// Static :
MyStaticClass.MyStaticFunction();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.