Skip to content

Instantly share code, notes, and snippets.

@rnarayana
Created August 31, 2016 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnarayana/5518327f9c7c94f8c2fde4ae7fee7733 to your computer and use it in GitHub Desktop.
Save rnarayana/5518327f9c7c94f8c2fde4ae7fee7733 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog40">
<arg key="configType" value="FILE" />
<arg key="configFile" value="NLog.config" />
</factoryAdapter>
</logging>
</common>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
using System;
using System.Diagnostics;
using System.Reflection;
using Common.Logging;
using PostSharp.Aspects;
namespace PostSharpInjectLogger
{
[Serializable]
public class LogExecutionTimeAttribute : OnMethodBoundaryAspect
{
[NonSerialized]
public static Func<ILog> GetLogger;
private string className;
private string methodName;
public LogExecutionTimeAttribute()
{
// Setting AspectPriority explicity avoids undeterministic behaviour
// when multiple aspects are applied, and avoids warning messages
this.AspectPriority = 1;
}
/// <summary>
/// Method executed at build time. Initializes the aspect instance. After the execution
/// of <see cref="CompileTimeInitialize"/>, the aspect is serialized as a managed
/// resource inside the transformed assembly, and de-serialized at runtime.
/// </summary>
/// <param name="method">Method to which the current aspect instance has been applied.</param>
/// <param name="aspectInfo">Unused.</param>
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
this.className = method.DeclaringType.FullName;
this.methodName = method.Name;
}
public override void OnEntry(MethodExecutionArgs args)
{
args.MethodExecutionTag = Stopwatch.StartNew();
base.OnEntry(args);
}
public override void OnExit(MethodExecutionArgs args)
{
Stopwatch sw = (Stopwatch)args.MethodExecutionTag;
sw.Stop();
var logger = GetLogger();
logger.DebugFormat(
"{0}.{1} for Id={2} executed in {3} seconds.",
this.className,
this.methodName,
args.Arguments[0],
sw.ElapsedMilliseconds / 1000.0);
base.OnExit(args);
}
}
}
using Common.Logging;
namespace PostSharpInjectLogger
{
/// <summary>
/// The base logger.
/// </summary>
public class LogFileLogger
{
public LogFileLogger(string runId)
{
NLog.MappedDiagnosticsContext.Set("RunId", runId);
this.LogInstance = LogManager.GetLogger("FileLogger");
}
public ILog LogInstance { get; set; }
}
}
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="nlog-internal.log">
<targets>
<target xsi:type="File"
name="FileLogger"
fileName="${basedir}/logfile_${mdc:item=RunId}.log"
header="Time,RunId,ThreadId,Counter"
layout="${message}"
deleteOldFileOnStartup="true"/>
</targets>
<rules>
<logger name="FileLogger" minlevel="Debug" writeTo="FileLogger" />
</rules>
</nlog>
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Common.Logging" version="3.3.1" targetFramework="net452" />
<package id="Common.Logging.Core" version="3.3.1" targetFramework="net452" />
<package id="Common.Logging.NLog40" version="3.3.1" targetFramework="net452" />
<package id="NLog" version="4.3.7" targetFramework="net452" />
<package id="NLog.Config" version="4.3.7" targetFramework="net452" />
<package id="NLog.Schema" version="4.3.7" targetFramework="net452" />
<package id="PostSharp" version="4.3.19" targetFramework="net452" />
</packages>
using System;
using System.Threading;
using System.Threading.Tasks;
namespace PostSharpInjectLogger
{
class Program
{
[LogExecutionTime]
private static void DoTask(int id, Random rand)
{
Thread.Sleep(rand.Next(0, 100));
}
private static void HelloTask(int id)
{
var log = new LogFileLogger(id.ToString()).LogInstance;
LogExecutionTimeAttribute.GetLogger = () => log;
var rand = new Random(id);
for (int i = 0; i < 100; i++)
{
DoTask(id, rand);
}
}
static void Main(string[] args)
{
Task t1 = Task.Factory.StartNew(() => HelloTask(1), TaskCreationOptions.LongRunning);
Task t2 = Task.Factory.StartNew(() => HelloTask(2), TaskCreationOptions.LongRunning);
Task t3 = Task.Factory.StartNew(() => HelloTask(3), TaskCreationOptions.LongRunning);
Task.WaitAll(t1, t2, t3);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment