Jun 1, 2017

Logging using Log4net in C# Console Application

This post lets get some insights on how to log errors using Log4net in our console application.
Lets get started by creating a console application in Visual studio.
Lets now configure log4net in our console application. To do this lets follow below steps.
1) Go to references and Manage nugget packages.



 2)Browse for Apache log4net and install the package. After this package is installed you will see a lognet dll added in your references.



3)We now need to add below lines of code to our app.config file in the ConfigSections tag.


4) In Program.cs lets try some code 

private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

static void Main(string[] args)
        {
            Logger.InfoFormat("Running as {0}", WindowsIdentity.GetCurrent().Name);
            try
            {
//your code here
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
             }
         
        }
     
We can also use 
Logger.Debug(),
Logger.Warn() etc.
     
    5) When the above code is run a log file is created in the location you specified in app.config.
in our case it is
       c:\\Logfile.txt
     
     Please try it and let me know how it worked for you.
Thanks all.
      

No comments: