Skip to content

Instantly share code, notes, and snippets.

@ksummerlin
Created September 20, 2017 13:00
Show Gist options
  • Save ksummerlin/1f9c651bfd7758f853f7fbd0abc6461d to your computer and use it in GitHub Desktop.
Save ksummerlin/1f9c651bfd7758f853f7fbd0abc6461d to your computer and use it in GitHub Desktop.
Example of using the CompilerServices attributes to automatically add the calling function name to logging information.
public static class LogExtentions
{
/// <summary>
/// Writes an information message to the logger of the form "methodCalled start: msg"
/// </summary>
/// <param name="log">The logger instance</param>
/// <param name="message">The optional message to use</param>
/// <param name="memberName">The member name to use (automatically set by the compiler)</param>
public static void InfoMethodStart(this ILog log, string message = null,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{
var msgSuffix = string.IsNullOrWhiteSpace(message) ? "." : $": {message}";
log.Info($"{memberName} start{msgSuffix}");
}
/// <summary>
/// Writes an information message to the logger of the form "methodCalled end: msg"
/// </summary>
/// <param name="log">The logger instance</param>
/// <param name="message">The optional message to use</param>
/// <param name="memberName">The member name to use (automatically set by the compiler)</param>
public static void InfoMethodEnd(this ILog log, string message,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{
var msgSuffix = string.IsNullOrWhiteSpace(message) ? "." : $": {message}";
log.Info($"{memberName} end{msgSuffix}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment