Code Monkey home page Code Monkey logo

log4net-loggly's Introduction

log4net-loggly

Custom log4net appenders for importing logging events to loggly. It’s asynchronous and will send logs in the background without blocking your application. Check out Loggly's .Net logging documentation to learn more.

Note: This library supports both .NET 4.0 and .NET Standard 2.0. Please see the section .NET Core Support below.

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>
<log4net>
    <root>
        <level value="ALL" />
        <appender-ref ref="LogglyAppender" />
    </root>
    <appender name="LogglyAppender" type="log4net.loggly.LogglyAppender, log4net-loggly">
        <rootUrl value="https://logs-01.loggly.com/" />
        <customerToken value="your-customer-token" />
        <tag value="your-custom-tags,separated-by-comma" />
        <logicalThreadContextKeys value="lkey1,lkey2" /> <!-- optional -->
        <globalContextKeys value="gkey1,gkey2" /> <!-- optional -->
    </appender>
</log4net>

If you want to append GlobalContext and/or LogicalThreadContext properties to your log you need to define the list of context properties in the configuration.

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

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

You can also use layout to render logs according to your Pattern Layouts

<layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger %message" />
</layout>

Add the following entry to your AssemblyInfo.cs

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Alternatively, you can add the following code in your Main method or in Global.asax file

log4net.Config.XmlConfigurator.Configure();

Create an object of the Log class using LogManager

var logger = LogManager.GetLogger(typeof(Class));

Send logs to Loggly using the following code

// send plain string
logger.Info("log message");

// send an exception
logger.Error("your log message", new Exception("your exception message"));

// send dictionary as JSON object
var items = new Dictionary<string,string>();
items.Add("key1","value1");
items.Add("key2", "value2");
logger.Info(items);

// send any object as JSON object
logger.Debug(new { Property = "This is anonymous object", Property2 = "with two properties" });

Flushing logs on application shutdown

Library is buffering and sending log messages to Loggly asynchronously in the background. That means that some logs may be still in buffer when the application terminates. To make sure that all logs have been sent you need to cleanly shutdown log4net logger using the following code:

logger.Logger.Repository.Shutdown();

This flushes any pending messages.

Advanced configuration

Library by default serializes and sends 4 levels of inner exceptions in case of warn/error log. If you want to change this number just add following configuration to config file to <appender> section

<numberOfInnerExceptions value value="10"/>

.NET Core Support:

Prerequisites:

  • Since this library support .NET Core target framework 2.0, make sure you are using either version 15.3.0 or higher of Visual Studio IDE 2017 or Visual Studio Code.

  • You must have installed the .NET Core 2.0 SDK and Runtime environment to develop and run your .NET Core 2.0 applications.

  • You may also have to install the .NET Core cross-platform development workload (in the Other Toolsets section). Please see the more details here.

Once you are done with the environment setup, now you are all set to create your application in .NET Core 2.0. Please follow the points below.

  • If you are using Visual Studio 2017 IDE then you can create a new .NET Core project by selecting New Project from File menu.

  • Visual Studio Code users can create a new project by running the below command on the project workspace terminal-

dotnet new console -o Application_Name

The dotnet command creates a new application of type console for you. The -o parameter creates a directory named Application_Name where your app is stored, and populates it with the required files.

  • If you are using Visual Studio 2017 IDE then you have to install the package log4net-loggly into your project from NuGet by running the command on Package Manager Console as shown below-
Install-Package log4net-loggly
  • If you are using Visual Studio Code then run the below command on the terminal to install the log4net-loggly package.
dotnet add package log4net-loggly
  • Now when you create an applicaton in .NET Core, there is no App.config file exist already in the project so you have to create one.

    (a) For Visual Studio 2017 users, you should right click on your project and create a Application Configuration File "App.config" on the root level of your project.

    (b) For Visual Studio Code users, you should simply create the same configuration file on the the folder structure where your another files exists.

  • You should simply add the below configuration code in your App.config file to configure LogglyAppender in your application. Make sure the configSections block is the first element of the configuration in app.config. This is a requirement set by .NET.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="LogglyAppender" />
    </root>
    <appender name="LogglyAppender" type="log4net.loggly.LogglyAppender, log4net-loggly">
      <rootUrl value="https://logs-01.loggly.com/" />
      <customerToken value="your-customer-token" />
      <tag value="your-custom-tags-separated-by-comma" />
      <logicalThreadContextKeys value="lkey1,lkey2" /> <!-- optional -->
      <globalContextKeys value="gkey1,gkey2" /> <!-- optional -->
    </appender>
  </log4net>
</configuration>

Note: If you are using Visual Studio 2017 IDE then your application will not be able to read configurations from this App.config file until you do the following-

  • Right click on your App.config file from Solution Explorer, go to Properties and select the Copy to Output Directory to Copy always, click Apply and hit the OK button.

If you are using Visual Studio Code then you don't need to do the extra settings for App.config file.

  • As compare to .NET Frameworks, in .NET Core you don't need any AssemblyInfo.cs file to add the below code in-
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

The above code line allows the application to read the configuration from App.config file. In .NET Core applications, we will be reading the configuartions in a different way which is stated below-

  • Add the following code inside the main method of your application file i.e. Program.cs-
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
log4net.Config.XmlConfigurator.Configure(logRepository, new FileInfo("App.config"));

Running the application in Visual Studio 2017 IDE is easy since you just need to click on the Start button to run your application.

If you are using Visual Studio Code then you have to run the below command on the terminal to run your .NET Core application-

dotnet run

And that's it. After doing this, you will see your .NET Core application logs flowing into Loggly.

log4net-loggly's People

Contributors

drewburlingame avatar giladwe avatar jgarcilazo avatar katulus avatar mend-for-github-com[bot] avatar mostlyjason avatar shwetajain148 avatar swankmotionpictures avatar urigrumble avatar varshneyjayant avatar

Stargazers

 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

log4net-loggly's Issues

FileNotFoundException on log4net.dll when running inside other application

Hi there,

I'm developing an addin for an existing application and I'm currently in the process of adding log4net. I'd love to be able to log to Loggly as well.

From my current understanding, my plugin isn't a complete application and therefore app.config doesn't work for configuring log4net. I got it writing to a text file using this example. Now as soon as I add a reference to log4net.loggly, I get a FileNotFoundException on the log4net dll. It only works when I copy the dll manually to the host application folder.

This my code to initialize the LogglyAppender (plus a "using log4net.loggly;" ):

            var logglyAppender = new LogglyAppender
            {
                RootUrl = "https://logs-01.loggly.com/",
                InputKey = "<my input key>",
                Tag = "<my tag>",
                Layout = patternLayout
            };

            logglyAppender.ActivateOptions();
            hierarchy.Root.AddAppender(logglyAppender);

Can this be caused by the way you handle references? What can I change in your or my code to get this working without copying the dll?

Observed Memory Leak in WCF

When we include the loggly-log4net's logglyAppender in our log4net config, it results in a memory leak. Removing it resolves the leak. Please let me know if you need any additional information to investigate this issue.

Can't format json fields

Hi,

It seems we can't format the resulting Json as the LogglyFormatter sets particular properties and dumps everything we pass into the message string.

Is it possible to override with our own formatter?
Or just take in an object to be serialized as json to be sent?

Garbage collection every time logs are appended

While investigating some performance issues with a website in am currently working on I discovered that the implementations of LogglyClient and LogglySendBufferedLogs both call GC.Collect() after appending new data.

This is especially bad for applications which produce quite verbose log output as it can trigger constant garbage collections to happen in all 3 generations. In addition under circumstances where the application error rate increases for any reason there is potential for additional garbage collections to worsen the situation.

Best practice guidelines from Microsoft are to only call GC.Collect() for "unique situations and testing" so can these calls be removed, or at least be made configurable?

On a side note, the same files also make calls to Console.WriteLine() if an error occurs when sending. Would it make sense for these to be replaced by something like Debugger.Log()?

Should I call Shutdown on each logger instance?

Hello.
I'm using log4net loggly in several projects and recently noticed that not all of my messages show up on the dashboard (the last few of them weren't there). I waited a long time and there's no sign of them, so it's unlikely to be a service issue.
I found in the docs I should call logger.Logger.Repository.Shutdown(); before exiting the application. I use separate logger instance for each of my classes. Should I call Shutdown only once for the entire app or for each of those separate logger instances?

I use 7.2.3 for the moment.

.NET Standard 1.x

Hi guys,
Could you please add support of .NET Standard 1.x?
It would be very useful for those who want to use Loggly on Linux from .net

Changed Tag is not used after ActivateOptions

Hi

We have a scenario where we would like to change the tag that is used. I can get the logger instance by calling this:
var logglyAppender = (log4net.LogManager.GetRepository().GetAppenders().FirstOrDefault(appender => appender.GetType() == typeof(LogglyAppender)) as LogglyAppender);

I have then access to the properties of the logger and can change the tag(s). My expectation was that after calling ActivateOptions the new tags are used, but the tags that are reported to loggly don't change.

Regards Adrian

.Net Core SDK 2.1 and 2.2 Compatibility

For the .NET Core Support Documentation, can you please verify if it supports higher .NET core SDK and Runtime version (2.1, 2.2) or was it only specific to 2.0 version?

Raw message rendering in loggly still broken

I am afraid, even after bumping to v9.0.0, there are still some issues with "raw message" rendering in loggly. (It's much better than 8.0.0, so thumbs up for the fix)

In 9.0.0, the raw message section seems to be "json compressed" with no whitespaces whereas version 7.0.0 used to have a prettified json with each prop split to a separate line.

Any solutions planned for this? Is there something we can do to control that (as I skimmed through your code, I couldn't find any flags relevant though)?

Regarding setting up with Visual Studio Code / Command line

I am trying to set up the application to log messages through docker.
My Configuration

  • DotNET Core (2.1.403) docker latest one.

I don't use visual studio code inside my docker but command line Vim editor. I am exactly following the steps but looks like log is not generating in loggly. (I have replaced key also).

I don't have to do anything for App.config except updating with a key, Please check and update.

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.