GithubHelp home page GithubHelp logo

net-commons / common-logging Goto Github PK

View Code? Open in Web Editor NEW
648.0 73.0 204.0 36.67 MB

A portable logging abstraction for .NET

Home Page: http://net-commons.github.io/common-logging

License: Apache License 2.0

C# 86.94% Visual Basic 0.02% Batchfile 0.18% XSLT 3.34% HTML 9.52%

common-logging's Introduction

Common.Logging .NET

Project Build Status

Build status

*Note: Build may periodically fail due to issues with the code-coverage tooling (NCover) being unable to reliably connect to the test-runner during test-runs on the CI server platform we've selected (Appveyor). Work continues to investigate this further, but until resolved properly visitors are advised to discount failing builds reported here.

Introduction

Provides a simple logging abstraction to switch between different logging implementations. There is current support for log4net, NLog, Microsoft Enterprise Library logging, Microsoft Application Insights, Microsoft Event Tracing for Windows, and Serilog.

Additionally Common.Logging comes with a set of base classes making the integration of any log system a breeze.

See also

Console Quickstart

This demonstrates how to configure your app to log using the built in Common.Logging console adapter.

1) Install Common.Logging via NuGet

Either open the Package Management Console and enter the following or use the built-in GUI

NuGet: PM> Install-Package Common.Logging

2) Register and configure Common.Logging

Then add the relevant sections to your app.config or web.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
    </sectionGroup>
  </configSections>

  <common>
    <logging>
      <factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging">
        <arg key="level" value="INFO" />
        <arg key="showLogName" value="true" />
        <arg key="showDateTime" value="true" />
        <arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:fff" />
      </factoryAdapter>
    </logging>
  </common>

</configuration>

NLog Quickstart

There are different packages for each major NLog version. Install the correct package for your referenced NLog version. This example installs the adapter for NLog v4.1:

PM> Install-Package Common.Logging.NLog41

If you are using NLog v4.0, you should install the Common.Logging.NLog40 package and so on.

NB: Because NLog is using semver and the same strong name for every major version, Common.Logging.NLog40 and Common.Logging.NLog41 works for all NLog 4.x version. Common.Logging.NLog41 is the recommend version

The app config should then have a common logging section like below. Be sure to match the factoryAdapter type with your installed Common.Logging.NLogXX version.

<common>
    <logging>
      <factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog41">
    	<arg key="configType" value="INLINE" />
      </factoryAdapter>
    </logging>
</common>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...
</nlog>

Application Insights Quickstart

There are different packages for each major Application Insights version. Install the correct package for your referenced Application Insights version. This example installs the adapter for Application Insights v0.17:

PM> Install-Package Microsoft.ApplicationInsights -Version 0.17.0

The app config should then have an Application Insights section like below. Be sure to set the InstrumentationKey with your InstrumentationKey retrieved from Application Insights portal https://portal.azure.com.

<common>
    <logging>
      <factoryAdapter type="Common.Logging.ApplicationInsights.ApplicationInsightsLoggerFactoryAdapter, Common.Logging.ApplicationInsights">
    	<arg key="InstrumentationKey" value="[YOUR APPLICATION INSIGHTS INSTRUMENTATION KEY]" />
      </factoryAdapter>
    </logging>
</common>

See module documentation and Source Forge for other factoryAdapters and their configuration values

Solution Layout

  • bin contains the Common.Logging distribution dll files
  • doc contains reference documentation.
  • shared contains shared nant build scripts
  • modules contains the sourcecode for Common.Logging.XXXX modules
  • redist contains redistributable assemblies like log4net for your convenience

The Common Infrastructure Libraries for .NET are released under the terms of the Apache Software License (see license.txt).

Building

  • Clone the GitHub repository
  • Install Silverlight SDK 5
  • [Optional] Install Java for the documentation builder
  • Create a strong name key. c:\netcommon>sn -k common.net.snk
  • Build the the solution. c:\netcommon>build-release.cmd

common-logging's People

Contributors

304notmodified avatar aaronmell avatar adamralph avatar adrianhopebailie avatar arithmomaniac avatar aseovic avatar bbaia avatar bradwilson avatar brantburnett avatar cd21h avatar daniel-svensson avatar dennis-gr avatar eeichinger avatar froggiefrog avatar giorgistoynev avatar ioancrisan avatar joelbourbon avatar keichinger avatar lahma avatar meixger avatar mihailsm avatar rhyscorke avatar rpaterlini avatar sbohlen avatar serra avatar tdupont750 avatar wied03 avatar zenima avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

common-logging's Issues

Could not load type 'Common.Logging.ILog'

I recently updated Common.Logging from NuGet and I now get this error message no matter what I do:

Could not load type 'Common.Logging.ILog' from assembly 'Common.Logging, Version=3.0.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e'.

web.config is shown looking for the correct version so I'm just stuck on why it's complaining.

Code Analysis - Specify IFormatProvider

Code Analysis - Specify IFormatProvider

In short, is there any way (other than wrapping my log calls into another class) to specify CultureInfo.InvariantCulture to logging statements?

Explanation:
In our app we display a log of logging statements with data from DB.
So we have something like this:

private static readonly ILog Logger = LogManager.GetCurrentClassLogger();
...
...
Logger.Warn(m => m("Customer [id: {0}] not found! Please check activation policy [name: \"{1}\", id: {2}]", customer.Id, policy.Name, policy.Id));
...
...

After turning on "All rules" for Conde Analysis the Logger statements are now generating following

CA1305  Specify IFormatProvider 
Because the behavior of 'ILog.Warn(Action<FormatMessageHandler>)' could vary based on the current user's locale settings, replace this call in 'Program.Main(string[])' with a call to 'ILog.Warn(IFormatProvider, Action<FormatMessageHandler>)'. 
If the result of 'ILog.Warn(IFormatProvider, Action<FormatMessageHandler>)' will be based on input from the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider' parameter. 
Otherwise, if the result will based on input stored and accessed by software, such as when it is loaded from disk or from a database, specify 'CultureInfo.InvariantCulture'.
MyCompany.MyApp Program.cs  44

To resolve this you have to

option 1:
Add IFormatProvider to all calls like so

Logger.Warn(CultureInfo.InvariantCulture, m => m("Customer [id: {0}] not found! Please check activation policy [name: \"{1}\", id: {2}]", customer.Id, policy.Name, policy.Id));

This makes codebase less readible, statements start wrapping when doing formatting, and you have to add "using System.Globalization" to each class...

option 2:
Ignore the rule by adding a suppression (which is not an option because of the way Code Analysis works (you have to exclude each call, ending up with suppression file that has thousands of lines))

option 3:
"Re-wrap" all logging calls into my own logging "facility" that will add IFormatProvider

So call me lazy :) but my question if following:
Since there is already method signature that allows supplying IFormatProvider, would it be possible for other methods to use default one (like CultureInfo.InvariantCulture)?

NuGet Version-Neutral Package Update Strategies

This Wiki page identifies the background against which we must consider this problem: https://github.com/net-commons/common-logging/wiki/Common.Logging-Packaging-and-Versions

This WIki page https://github.com/net-commons/common-logging/wiki/NuGet-Packaging-Update-Strategies lists several strategies for trying to mitigate this problem as well as what we see as some of the PROs and CONs for each approach. We're opening this issue here for there to be a single place to discuss this issue (and hopefully come to a conclusion re: which the community feels would be best to pursue).

TypeLoadException With Common.Logging.Log4Net 2.0.1 and Common.Logging 2.2.0

It appears that the Common.Logging.Log4Net nuget package is incompatible with Common.Logging 2.2.0.

When calling LogManager.GetCurrentClassLogger() a TypeLoadException is thrown:

Could not load type 'Common.Logging.Factory.AbstractCachingLoggerFactoryAdapter' from assembly 'Common.Logging, Version=2.2.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e'.":"Common.Logging.Factory.AbstractCachingLoggerFactoryAdapter

 at Common.Logging.ConfigurationSectionHandler.ReadConfiguration(XmlNode section) in c:\_oss\common-logging\src\Common.Logging\Logging\ConfigurationSectionHandler.cs:line 134
   at Common.Logging.ConfigurationSectionHandler.Create(LogSetting parent, Object configContext, XmlNode section) in c:\_oss\common-logging\src\Common.Logging\Logging\ConfigurationSectionHandler.cs:line 204
   at Common.Logging.ConfigurationSectionHandler.System.Configuration.IConfigurationSectionHandler.Create(Object parent, Object configContext, XmlNode section) in c:\_oss\common-logging\src\Common.Logging\Logging\ConfigurationSectionHandler.cs:line 226
   at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)

I'm using the following app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
    </sectionGroup>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
        <arg key="configType" value="INLINE" />
      </factoryAdapter>
    </logging>
  </common>
  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
    </appender>
    <root>
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.2.0.0" newVersion="2.2.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

The exception can be reproduced using a simple console application:

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var logger = LogManager.GetCurrentClassLogger();
                logger.Info("Hello world");
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine(exception);
            }
        }
    }

NuGet - Common.Logging.NLog31 incompatible with PCL

I'm trying to use Common.Logging.Portable (as my core library is PCL), but it appears that Common.Logging.NLog31 doesn't play nicely with C.L.Portable. It wants to have Common.Logging; obviously, having both C.L and C.L.Portable in the same project is Not Fun.

Any help would be appreciated!

Events / Context. Can Common Logging support it?

Hello,

Would be possible to include Events in Common Logging? For example, in NLog is:

LogEventInfo eventInfo = new LogEventInfo { Level = LogLevel.Error, Exception = exception, Message = exception.Message };       
eventInfo.Properties["data"] = "data";

I think in Log4Net is called Context ...

Thank You,
Miguel

Multiple Factories / Appenders

I have a situation where I would want to use log4net for colored console output and entlib for persistent logging. I don't see something that allows multiple factories acting like the log4net AppenderCollection. This would be a nice addition and maybe somebody already has made this but I could not find it.

AbstractCachingLoggerFactoryAdapter.GetLogger can return null

EDIT -- Disregard. Didn't realize I was working from a fork created by a colleague. Sorry for any confusion.

I noticed this while trying to use CommonLoggingTraceListener to redirect messages from a named TraceSource to NLog. I could be mistaken, but I believe the actual issue is rooted in how AbstractCachingLoggerFactoryAdapter uses WeakReference. In particular, it never checks the reference's Target property against null. In any case, the listener appears to assume that the returned logger is not null, because this happens:

System.NullReferenceException was unhandled HResult=-2147467261 Message=Object reference not set to an instance of an object. Source=Common.Logging StackTrace: at Common.Logging.Simple.CommonLoggingTraceListener.Log(TraceEventType eventType, String source, Int32 id, String format, Object[] args) at Common.Logging.Simple.CommonLoggingTraceListener.TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, String message) at System.Diagnostics.TraceSource.TraceEvent(TraceEventType eventType, Int32 id, String message) at --- SNIP ---

Repro:

ILog log = LogManager.GetLogger("test");
Debug.Assert(log != null); // ok
log = null;
GC.Collect();
GC.WaitForFullGCComplete();
log = LogManager.GetLogger("test");
Debug.Assert(log != null); // fail

Booleans for IsWarnEnabled etc not working with EntLib 5

Hi,

I downloaded the Nuget package for a new ASP .NET MVC 4 Web application with framework 4.5.
I als downloaded the EntLib 5 package.
I added the config sections. Everything default but only the switchvalue of entlib to critical for testing this issue. I also tried Warning, error etc.

I used this code:
ILog log = LogManager.GetLogger("General");
if (log.IsWarnEnabled)
{
//Some very heavy code is done here for debugging reasons....

 log.Warn("Only when warning is enabled");

}

If I set a breakpoint in the if statement. The breakpoint is hit. So every code that is in the if statement is fired.

If I read your documentation (Chapter 1.3. Using Common.Logging API) right, the if statement should not be executed. Correct me if i'm wrong.
Everything else will work fine because the warning isn't showing up in the Eventlog.

Hopefully you understand my issue. I only want to step into the if statement when the switchvalue is correct.

Thanks

ETA on new NuGet release?

Is there any planned ETA on a new NuGet release?

There are conflicts in both the log4net and nlog integration assemblies, with newer versions of common.logging.

How are people getting round this at the moment? Am I going to need to write my own log4net adapter?

Xamarin support

Please add support for Xamarin 3. It shares the same capabilities as win8 and wpa81, so should be as easy as adding a new folder in the nuget lib folder called portable-net45+netcore45+wpa81+MonoAndroid1+MonoTouch1 (taken from http://embed.plnkr.co/03ck2dCtnJogBKHJ9EjY/preview) and dropping the dll in there.

Logging with lambda expression

Hi, I am using common.logging (with log4net 1.2.10). Sometimes, when I try to log a string which I received from an external service, the logging system throws an exception. I am not sure if the exception originates from common.logging or log4net.

For example, I do:
string s = service.GetName();
log.Debug(m => m("servicename=" + s));

It appears this exception occurs because the string contains ‘{‘ and/or ‘}’ characters. Can this be correct? (Maybe the name I get is "Service81{loc17}").

Here is a stacktrace:

<log4net.Error>Exception rendering object type [Common.Logging.Factory.AbstractLogger+FormatMessageCallbackFormattedMessage]System.FormatException: Input string was not in a correct format.
at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at Common.Logging.Factory.AbstractLogger.FormatMessageCallbackFormattedMessage.FormatMessage(String format, Object[] args)
at Alpha.Portal.ServiceAccess.Search.<>c__DisplayClass6.b__5(FormatMessageHandler m)
at Common.Logging.Factory.AbstractLogger.FormatMessageCallbackFormattedMessage.ToString()
at log4net.ObjectRenderer.DefaultRenderer.RenderObject(RendererMap rendererMap, Object obj, TextWriter writer)
at log4net.ObjectRenderer.RendererMap.FindAndRender(Object obj, TextWriter writer)</log4net.Error>

After looking in common-logging source code (and from the stacktrace), it appears this stems from class AbsractLogger, in the method:

private string FormatMessage(string format, params object[] args)
{
cachedMessage = string.Format(formatProvider, format, args);
return cachedMessage;
}

where obviously the { } are being interpreted as part of a format string - and thereby giving an error.

What is a good workaround? As I have found out, I can't guarantee what strings I have that I want to log. Do I always need to check for format parameters - or avoid using the (otherwise extremely useful) lamda expression call to common-logging?

Thanks,
Peter

log4net locked version

Hello,

We've got several projects we're maintaining that have been depending on Common.Logging and Common.Logging.Log4Net. We've also got a couple of other Nuget packages incorporated that have their own dependencies on log4net.

In the interest of keeping up with our sources, we want to keep up to date with log4net, but we are finding that C.L.L4N, in particular, is holding us back; i.e. log4net (= 1.2.10).

We can disable logging for the time being until we can find a suitable migration path forward, but if there's any way we can stay current with log4net and still maintain our migration path with net-commons, that would have the least impact of all.

Edit:
Common.Logging: 2.0.0 (sometimes 2.2.0, but that's from Nuget blind pulls)
Common.Logging.Log4Net: 2.0.1, which at least depends on Common.Logging (>= 2.0.0)

Thank you...

Best regards.

GetCurrentClassLogger possible NRE

LogManager.GetCurrentClassLogger uses the DeclaringType from the method info as the current class, but in .net 4.0 and later include DynamicMethod.DeclaringType which is always null.

This causes GetCurrentClassLogger to throw NullReferenceException when invoked from a dynamic method.

I've seen this problem in conjunction with Spring Framework with a proxied type, as in this example stack trace:

Object reference not set to an instance of an object.
at Common.Logging.Factory.AbstractCachingLoggerFactoryAdapter.GetLogger(Type type)
at Common.Logging.LogManager.GetCurrentClassLogger()
at _dynamic_MyExampleType..ctor(Object[] )
at Spring.Util.ObjectUtils.InstantiateType(ConstructorInfo constructor, Object[] arguments) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Util\ObjectUtils.cs:line 252

Since no declaring type will be available, perhaps throwing a more specific exception instead of NRE is the best fix. Code that worked on .net 3.5 stops working on .net 4.0 because of this bug.

External configuration file

Hi All,

I intend to use the common logging framework within Microsoft BizTalk. The problem is that all of the BizTalk applications use one config file instead of one app.config per application (this is the way Biztalk works, not a way I implemented it).

To maintain configuration settings per application I create a section group per application part and redirect that to an external file. Each application retrieves settings from that specific section.

I try to use the common logging framework within that architecture, but it seems to be fixed on common/logging within the root section. It seems possible to reset the logmanager (Common.Logging.LogManager.Reset), specifying an IConfigurationReader, but I see now way of using a reader for this specific external section.

For instance, I would like to use:
configSections
sectionGroup name="MyAppPart"
section name="MyAppPart.Logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"
/sectionGroup

MyAppPart.Logging file="d:\configurations\MyAppPart.Logging.config"

Within the global configuration file, having a “MyAppPart” per application pointing to different configuration files.

That content could for instance be:

MyAppPart.Logging
factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net1211"
arg key="configType" value="FILE-WATCH" /
arg key="configFile" value="D:\configurations\MyAppPart.Logging.log4net.config" /
/factoryAdapter
/MyAppPart.Logging

And then myapppart.logging.log4net.config would contain the log4net specific logging. Setting up the configuration like this works, and I could easily get that configuration like:

            System.Configuration.Configuration config =
        ConfigurationManager.OpenExeConfiguration(
        ConfigurationUserLevel.None);
            System.Configuration.ConfigurationSection section = config.GetSection("AdConvert/TRS.ADOReplacement.Logging");

But it’s not possible to tell the logging framework to use that configuration section. It would be great if that could be possible.

JSON output

It would be cool if the output can be switched to a JSON object in order to simplify logging to Logstash

I wonder if it can be achieved by a custom IFormatProvider?

My idea:

DataContractJsonSerializer ser = new DataContractJsonSerializer(arg.GetType());
using (MemoryStream ms = new MemoryStream())
{
  ser.WriteObject(ms, arg);
  var json = Encoding.Default.GetString(ms.ToArray());
  ms.Close();
  return json;
}

NLog ${callsite} support

When NLog's ${callsite} is used, the logged callsite is Common.Logging's method instead of the caller.

Is it possible to fix using an approach such as:
http://stackoverflow.com/questions/5132759/nlog-callsite-information
http://nlog-forum.1685105.n2.nabble.com/NLog-and-Commons-Logging-question-td1685331.html
So that people won't add another wrapper to work around this?

Edit: Solution had Common.Logging.NLog NuGet package instead of Common.Logging.NLog20 package in it, after correcting this problem did not reoccur.

Keyfile is missing

When I ran build-release.cmd, it gave me the key file missing error:
project.sign='true' but keyfile D:\kerry\workshop\common-logging/Common.Net.snk is missing

Can I generate the keyfile by myself?

Possible Issues with Common.Logging / Common.Logging.NLog20 NuGet packages

I think there may be an error in the information added to web.config when the indicated NuGet packages are added to a project.

When the package is added to the project, the following is added to web.config:

    <dependentAssembly>
      <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
    </dependentAssembly>

Unfortunately this seems to result in the following error at run-time :

Parser Error Message: An error occurred creating the configuration section handler for common/logging: Unable to create type 'Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20'

I had to make the following change in order to resolve the issue (note the 'oldVersion' attribute)...

    <dependentAssembly>
       <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-65535.65535.65535.65535" newVersion="2.0.0.0" />
      </dependentAssembly>

Support portable class libraries (PCL)

Allow common.logging to be used by portable libraries in order to allow it to be used on other platforms (Silverlight, windows store apps ..) than the .net desktop.

To do so all (portable) core-functionality should be moved into a portable assebly while platform specific functionallity is moved to platform specific assemblies.

So far @ioancrisan has made good progress towards making common.logging more portable by adding simple Silverlight and portable support and this is something we should be able to utilize.

See #21 for his contribution as well as some discussion about how to achive portable class lirbary support

LogLevel

Can we change LogLevel into a bit flag enum? That way it would be nice to log specific levels as a group instead of one, all, or none. It is a simple thing to do and would provide a great benefit.

NLog ${callsite} support on x64

Same issue as #18. I fixed it by following the instruction to use NLog20. However, after I switched over to x64, the solution stopped working.

By switching to x64, I meant I removed x86 in the .csproj, so the project compiles for all platforms.

Signed binaries

I want to deploy Common.Logging on our customer's computers. They only accept signed libraries on their computers. The download package does not contain signed libraries.

Is it allowed to sign the downloaded libraries with my company signatures?

Leaky abstraction

FormatMessageCallbackFormattedMessage and FormatMessageCallback in AbstractLogger is a leaky part of the abstraction. Simple example:
var a = new A();
Log.Info(a); // peace of cake
Log.Info(handler => handler(a)); // won't even compile

More complicated example:
var a = new A();
Log.Info(a); // I want to log A => my logging system will receive A
Log.Info(handler => handler(a.ToString())); // I want to log A.ToString() => my logging system will receive... FormatMessageCallbackFormattedMessage?!
Log.Info(null); // I want to log null => my logging system will receive... FormatMessageCallbackFormattedMessage... again.

Even more complicated example:
var a = new A();
a.Part = 1;
Log.Info(handler => handler(a.Part.ToString()));
a.Part = 2;
a = new A();
a.Part = 3;
// guess: Will logging system log 1,2 or 3?
// the right answer is: Logging system will log FormatMessageCallbackFormattedMessage with closure inside it. And in some synthetic cases it is possible to modify closure before actual logging occurs.

Operation could destabilize the runtime.

When I follow the steps below, the system fails with an exception:

System.Security.VerificationException : Operation could destabilize the runtime.
  1. Create a new Windows Service, using the .NET 4 framework
  2. Use NuGet to add Common.Logging package
  3. In the OnStart, add the following code:
LogManager.Adapter = new NoOpLoggerFactoryAdapter();
ILog log = LogManager.GetCurrentClassLogger();
log.Debug("hello world");

Observe that the service fails to start with the exception above. This was discovered using other frameworks that depend on Common.Logging.

Common.Logging Version: 2.1.2
Runtime Version: .NET 4.0
Architecture: x86, x64 and AnyCPU

Inefficiency code in 'ErrorFormat' (and other XXXFormat)

public virtual void ErrorFormat(string format, params object[] args)
{
    if (this.IsErrorEnabled)
    {
        this.Write(LogLevel.Error, new StringFormatFormattedMessage(null, format, args), null);
    }
}

every time this XXXFormat is called, a new StringFormatFormattedMessage instance is constructed, which do nothing but call string.Format.
Why not call string.Format directly since this is called only once. the CachedMessage had not even been used.

public override string ToString()
{
    if ((this.cachedMessage == null) && (this.Message != null))
    {
        this.cachedMessage = string.Format(this.FormatProvider, this.Message, this.Args);
    }
    return this.cachedMessage;
}

Execution from a network drive

Hi,

I've to run an application from a network drive and can't change something on the pc trust settings. I use your logging in combination with log4net and Spring and I'm getting an exception like 'That assembly does not allow partially trusted callers.' from common.logging.
I thought about building the common.logging ddls by myself using f.e. the [assembly:AllowPartiallyTrustedCallers] settings. But I don't have the .snk file so the dlls would not be strongly named. But I need it strongly named cause I redirect them in my application for another third party dll.
Is there a way to solve my problem or is there a better approach?

Thx for the help,
Nergal

Strong name

Without a strong name a commong-logging reference can't be added to a project that has a strong name.

Thanks
michele

Add Change Log for 2.2.0

Common.Logging 2.2.0 has been released on nuget.org with a new assembly Common.Logging.Core. But the document has not been updated yet. Just a few sentences on what's been changed/added will help a lot. Thanks.

Using in a multi-layer application

I'd like to use this library in an application I'm working on. It currently consists of three subprojects:

  • Web
  • API
  • Core

Core is used by the other two; it contains common objects such as models, data access, and infrastructure such as logging. Having added Common.Logging and NLog 3 (with the appropriate adapter) to the Core project, I haven't access to the logging capabilities from the other two projects - obviously since the logging support was added to the core project only.

I can see two ways to extend logging support to the Web and API projects:

  • create my own logging interface (e.g. ILog) and implement it, possibly as a thin wrapper around the actual logging library; would have to add my own functions to mirror those already available
  • extend the logging library classes into my own class versions - no extra functionality, but get everything already available

Either way there's redundancy - adding an abstraction over an abstraction. Would one of the above options be the lesser of the two evils, or is there another route I might take?

Example for configuration for NLog out of date

I just installed Common.Logging to interface to NLog, using the Nuget package
Common.Logging.NLog20

To figure out the additional configuration I had to do in my web.config, I followed the example at
http://netcommon.sourceforge.net/docs/2.1.0/reference/html/ch01.html#logging-adapters-nlog

However, this refers to NLog10, which the Nuget package didn't install. This lead to an obtuse error message which took some time to resolve.

<configuration>
  <common>
    <logging>
>>>>>>>>>>>>>
      <factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog10">
 <<<<<<<<<<<
        <arg key="configType" value="FILE" />
        <arg key="configFile" value="~/NLog.config" />
      </factoryAdapter>
    </logging>
  </common>
</configuration> 

IMHO, the example should refer to NLog20, not NLog10.

I appreciate that at the top of this section, it refers to the 2 implementations, for NLog20 and NLog10. But that is very easy to overlook.

I also appreciate that changing the example to NLog20 will cause pain to people installing Common.Logging for NLog10. However,

  • NLog20 was released on July 18 2011, over 2 years ago
  • Less than one third of all NLog downloads have been for NLog10

NLog.TargetWithLayout has moved

Commons.Logging.NLog seems to be trying to load NLog.TargetWithLayout, but that class has moved to NLog.Targets.TargetWithLayout. Consequently, an exception is thrown by the reflection loader.

Add coloured console output to simple logging

ConsoleOutLoggerFactoryAdapter is great for quickly plugging in a console logger.

It would be even greater if we could have a simple ColoredConsoleOutLoggerFactoryAdapter. Different colours for each logging level is just so so pretty and readable 😉.

I understand that you probably don't want to lump too many simple loggers into the library and they should be kept simple, but I think this implementation would indeed be simple and lots of people would use it.

Alternatively, we could have a new constructor for ConsoleOutLoggerFactoryAdapter with a bool useColour parameter.

backwards compat break with 2.2 factor adapters

I am having trouble finding any documentation on what actually changed with Common.Logging 2.2. Specifically, what changed with implementing factory adapters? I was running with common logging 2.1.2 and my factor adapter and configuration worked. And now it doesn't with common logging 2.2 (from NuGet).

This is the error I get:

An exception of type 'Common.Logging.ConfigurationException' occurred in Common.Logging.Core.dll but was not handled in user code

Additional information: Unable to create instance of type Candor.WindowsAzure.Logging.Common.Table.CloudTableLoggerFactoryAdapter. Possible explanation is lack of zero arg and single arg NameValueCollection constructors

Inner exception:
Constructor on type 'Candor.WindowsAzure.Logging.Common.Table.CloudTableLoggerFactoryAdapter' not found.

I do have a constructor, and it worked with 2.1.2. What kind of constructor do I need to add?

Here is my code repository:
https://github.com/michael-lang/candor-common/tree/master/Candor.WindowsAzure.Logging.Common/Table

And the current code noted in the common logging exception:

public class CloudTableLoggerFactoryAdapter : AbstractCachingLoggerFactoryAdapter
{
    private readonly string _connectionName;

    public CloudTableLoggerFactoryAdapter(NameValueCollection properties)
    {
        _connectionName = properties["ConnectionName"];
    }
    protected override ILog CreateLogger(string name)
    {
        return new CloudTableLogger(_connectionName, name);
    }
}

Common.Logging.NLog20 doesn't work

Error:

An error occurred creating the configuration section handler for common/logging: Unable to create type 'Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20'

Bug in .NET 4 results in exception reading config from network share

*** NOTE: this issue report copied from net-commons mailing list ***

I have following problem found : Security exception on configuration reading when the application it is started from network share failure.

I try the basiclogging project using the EnterpriseLibrary

The only difference is that I use the outside definition of common logging configuration sections, that on local folder works without problems.

The exception comes on return ConfigurationManager.GetSection(sectionName); in defaultconfigutrationreadder.cs.

The problem it is an bug in System.Configuration described in http://support.microsoft.com/kb/2580188 with workaround

to use System.Configuration.Configuration.GetSection(sectionName).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.