Skip to content

Commit

Permalink
Merge pull request #19 from psquickitjayant/adding-contexts
Browse files Browse the repository at this point in the history
Adding contexts
  • Loading branch information
varshneyjayant committed Jan 20, 2016
2 parents 12cc099 + 0fc54c9 commit b4e9eec
Show file tree
Hide file tree
Showing 33 changed files with 26,865 additions and 33,353 deletions.
16 changes: 13 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Download log4net-loggly package from NuGet. Use the following command.
Install-Package log4net-loggly

Add the following code in your web.config to configure LogglyAppender in your application

```
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
Expand All @@ -20,10 +20,20 @@ Add the following code in your web.config to configure LogglyAppender in your ap
<appender name="LogglyAppender" type="log4net.loggly.LogglyAppender, log4net-loggly">
<rootUrl value="http://logs-01.loggly.com/" />
<inputKey value="your-customer-token" />
<tag value="your-custom-tag" />
<tag value="your-custom-tag" />
<logicalThreadContextKeys value="lkey1,lkey2" /> <!-- optional -->
<globalContextKeys value="gkey1,gkey2" /> <!-- optional -->
</appender>
</log4net>

```
To send **GlobalContext** and **LogicalThreadContext** properties in your log you need define the list of used properties in the configuration.

For GlobalContext Properties use
```<globalContextKeys value="gkey1,gkey2" />```

For LogicalThreadContext Properties
```<logicalThreadContextKeys value="lkey1,lkey2" />```


You can also use **layout** with in the Config to render logs according to your Pattern Layouts

Expand Down
6 changes: 4 additions & 2 deletions source/log4net-loggly-console/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@
</root>
<appender name="LogglyAppender" type="log4net.loggly.LogglyAppender, log4net-loggly">
<rootUrl value="http://logs-01.loggly.com/" />
<inputKey value="Your-Customer-Token" />
<inputKey value="customer-token" />
<tag value="log4net-test" />
<logicalThreadContextKeys value="LogicalThread1,InnerLogicalThreadContext" />
<globalContextKeys value="GlobalContextPropertySample" />
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC1}] - %message%newline" />
</layout>
</appender>
</log4net>
Expand Down
28 changes: 27 additions & 1 deletion source/log4net-loggly-console/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,29 @@
using System.Collections.Generic;
using System.Threading;
using log4net;
using log4net.Core;

namespace log4net_loggly_console
{
class Program
class GlobalContextTest : IFixingRequired
{
public object GetFixedObject()
{
return ToString();
}

public override string ToString()
{
return DateTime.UtcNow.Millisecond.ToString();
}
}

class Program
{
static void Main(string[] argArray)
{
GlobalContext.Properties["GlobalContextPropertySample"] = new GlobalContextTest();

log4net.Config.XmlConfigurator.Configure();

var log = LogManager.GetLogger(typeof(Program));
Expand All @@ -26,6 +42,7 @@ static void Main(string[] argArray)
Thread curntThread = Thread.CurrentThread;
curntThread.Name = "Inner thread 1";
ThreadContext.Properties["InnerThread1Context"] = "InnerThreadContext1Values";
LogicalThreadContext.Properties["InnerLogicalThreadContext"] = "InnerLogicalThreadContextValues";
using (ThreadContext.Stacks["NDC1"].Push("StackValue1"))
{
Expand All @@ -37,6 +54,15 @@ static void Main(string[] argArray)
}
}
using (LogicalThreadContext.Stacks["LogicalThread1"].Push("LogicalThread1_Stack"))
{
log.Info("logical thread context 1 stack");
using (LogicalThreadContext.Stacks["LogicalThread1"].Push("LogicalThread1_Stack_2"))
{
log.Info("logical thread context 2 stack");
}
}
log.Info("without ndc of inner thread 1");
});

Expand Down
4 changes: 3 additions & 1 deletion source/log4net-loggly/ILogglyAppenderConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ public interface ILogglyAppenderConfig
string UserAgent { get; set; }
int TimeoutInSeconds { get; set; }
string Tag { get; set; }
}
string LogicalThreadContextKeys { get; set; }
string GlobalContextKeys { get; set; }
}
}
2 changes: 2 additions & 0 deletions source/log4net-loggly/LogglyAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public class LogglyAppender : AppenderSkeleton
public string UserAgent { set { Config.UserAgent = value; } }
public int TimeoutInSeconds { set { Config.TimeoutInSeconds = value; } }
public string Tag { set { Config.Tag = value; } }
public string LogicalThreadContextKeys { set { Config.LogicalThreadContextKeys = value; } }
public string GlobalContextKeys { set { Config.GlobalContextKeys = value; } }

protected override void Append(LoggingEvent loggingEvent)
{
Expand Down
8 changes: 7 additions & 1 deletion source/log4net-loggly/LogglyAppenderConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,17 @@ public string RootUrl

public string Tag { get; set; }

public LogglyAppenderConfig()
public string LogicalThreadContextKeys { get; set; }

public string GlobalContextKeys { get; set; }

public LogglyAppenderConfig()
{
UserAgent = "loggly-log4net-appender";
TimeoutInSeconds = 30;
Tag = "log4net";
LogicalThreadContextKeys = null;
GlobalContextKeys = null;
}
}
}
90 changes: 49 additions & 41 deletions source/log4net-loggly/LogglyFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ namespace log4net.loggly
public class LogglyFormatter : ILogglyFormatter
{
private Process _currentProcess;
private ILogglyAppenderConfig _config;

public LogglyFormatter()
{
Expand All @@ -20,6 +21,7 @@ public LogglyFormatter()

public virtual void AppendAdditionalLoggingInformation(ILogglyAppenderConfig config, LoggingEvent loggingEvent)
{
this._config = config;
}

public virtual string ToJson(LoggingEvent loggingEvent)
Expand Down Expand Up @@ -78,20 +80,58 @@ private string PreParse(LoggingEvent loggingEvent)
var p = _loggingInfo as IDictionary<string, object>;
foreach (string key in _threadContextProperties)
{
//handling threadstack
if (ThreadContext.Properties[key].GetType() ==
typeof(log4net.Util.ThreadContextStack))
if ((ThreadContext.Properties[key] as IFixingRequired) != null
&& (ThreadContext.Properties[key] as IFixingRequired).GetFixedObject() != null)
{
string[] stackArray;
if (IncludeThreadStackValues(ThreadContext.Properties[key]
as log4net.Util.ThreadContextStack, out stackArray))
p[key] = (ThreadContext.Properties[key] as IFixingRequired).GetFixedObject();
}
else
{
p[key] = ThreadContext.Properties[key].ToString();
}
}
}

//handling logicalthreadcontext properties
if (this._config.LogicalThreadContextKeys != null)
{
var ltp = _loggingInfo as IDictionary<string, object>;
string[] _LogicalThreadContextProperties = this._config.LogicalThreadContextKeys.Split(',');
foreach (string key in _LogicalThreadContextProperties)
{
if (LogicalThreadContext.Properties[key] != null)
{
if ((LogicalThreadContext.Properties[key] as IFixingRequired) != null
&& (LogicalThreadContext.Properties[key] as IFixingRequired).GetFixedObject() != null)
{
p[key] = stackArray;
ltp[key] = (LogicalThreadContext.Properties[key] as IFixingRequired).GetFixedObject();
}
else
{
ltp[key] = LogicalThreadContext.Properties[key].ToString();
}
}
else
}
}

//handling globalcontext properties
if (this._config.GlobalContextKeys != null)
{
var gcp = _loggingInfo as IDictionary<string, object>;
string[] _globalContextProperties = this._config.GlobalContextKeys.Split(',');
foreach (string key in _globalContextProperties)
{
if (GlobalContext.Properties[key] != null)
{
p[key] = ThreadContext.Properties[key];
if ((GlobalContext.Properties[key] as IFixingRequired) != null
&& (GlobalContext.Properties[key] as IFixingRequired).GetFixedObject() != null)
{
gcp[key] = (GlobalContext.Properties[key] as IFixingRequired).GetFixedObject();
}
else
{
gcp[key] = GlobalContext.Properties[key].ToString();
}
}
}
}
Expand Down Expand Up @@ -203,38 +243,6 @@ private string GetMessageAndObjectInfo(LoggingEvent loggingEvent, out object obj
return message;
}

/// <summary>
/// Returns whether to include stack array or not
/// Also outs the stack array if needed to include
/// </summary>
/// <param name="stack"></param>
/// <param name="includeStackKey"></param>
/// <returns></returns>
private bool IncludeThreadStackValues(log4net.Util.ThreadContextStack stack,
out string[] stackArray)
{
if (stack != null && stack.Count > 0)
{
stackArray = new string[stack.Count];
for (int n = stack.Count - 1; n >= 0; n--)
{
stackArray[n] = stack.Pop();
}

foreach (string stackValue in stackArray)
{
stack.Push(stackValue);
}
return true;
}
else
{
stackArray = null;
return false;
}

}

/// <summary>
/// Tries to merge log with the logged object or rendered log
/// and converts to JSON
Expand Down
6 changes: 3 additions & 3 deletions source/log4net-loggly/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
[assembly: AssemblyTitle("log4net-loggly")]
[assembly: AssemblyDescription("Log4net client for Loggly Gen 2")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyCompany("log4net-loggly")]
[assembly: AssemblyProduct("log4net-loggly")]
[assembly: AssemblyCopyright("Copyright © log4net-loggly 2015")]
[assembly: AssemblyTrademark("")]
Expand All @@ -32,5 +32,5 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("7.0.0.0")]
[assembly: AssemblyFileVersion("7.0.0.0")]
[assembly: AssemblyVersion("8.0.0.0")]
[assembly: AssemblyFileVersion("8.0.0.0")]
6 changes: 3 additions & 3 deletions source/log4net-loggly/log4net-loggly.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\log4net.2.0.3\lib\net40-full\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.6.0.8\lib\net40\Newtonsoft.Json.dll</HintPath>
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.8.0.1\lib\net40\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
Expand Down
4 changes: 2 additions & 2 deletions source/log4net-loggly/packages.config
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.3" targetFramework="net40" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net40" />
<package id="log4net" version="2.0.3" targetFramework="net4" />
<package id="Newtonsoft.Json" version="8.0.1" targetFramework="net4" />
</packages>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading

0 comments on commit b4e9eec

Please sign in to comment.