Skip to main content

Use Log4Net in C# windows form Application

we are going to learn on how to use the Log4Net library for creating logs. Create a new windows form application in VS.

  1. Install Log4Net library
  2. Add to AssemblyInfo.cs 
  3. Configure in App.config
  4. Use in code 
Install Log4Net library
Then install the Log4Net library from the Nuget Package library.

  •           log4net by The Apache software foundation 2.0.8 (i installed the latest).


Add to AssemblyInfo.cs 
After installing this package, open up AssemblyInfo.cs file under the Properties folder and add the log4net assembly information into it (under the other assembly information.).
   [assembly: log4net.Config.XmlConfigurator(Watch=true)] 


Configure in App.config
Now, open the App.config file and enter required details for LogNet to work.

<configSections>  
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" /> </configSections>  
<!-- Log4net Logging Setup -->  
<log4net>  
    <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">  
        <file value="D:\\POC\\MVPProject\\MVPProject\\Log\\mylogfile.txt" />  
        <!-- the location where the log file would be created -->  
        <appendToFile value="true" />  
        <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />  
        <layout type="log4net.Layout.PatternLayout">  
            <conversionPattern value="%date [%thread] %level %logger - %message%newline" /> </layout>  
        <filter type="log4net.Filter.LevelRangeFilter">  
            <levelMin value="INFO" />  
            <levelMax value="FATAL" /> </filter>  
    </appender>  
    <root>  
        <level value="DEBUG" />  
        <appender-ref ref="FileAppender" /> </root>  

</log4net>  

Use in code 
Use it in form like below,
public partial class Form1 : Form
    {
        public log4net.ILog log;


        public Form1()
        {
            log4net.Config.BasicConfigurator.Configure();
            log = log4net.LogManager.GetLogger(typeof(Program));
            InitializeComponent();

            log.Info("form constructor");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            log.Info("form load");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            log.Info("button click");
        }
    }


Ref : https://haacked.com/archive/2006/01/13/SettingUpLog4NetForMultiLayeredApplications.aspx/
https://www.c-sharpcorner.com/blogs/use-log4net-in-c-sharp-console-application

RollingFileAppender :
<log4net>
<root>
 <level value="DEBUG" />
 <appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
 <param name="File" value="C:\Try\logger\logger\bin\Debug\log.txt" />
 <param name="AppendToFile" value="true" />
 <rollingStyle value="Size" />
 <maxSizeRollBackups value="10" />
 <maximumFileSize value="10MB" />
 <staticLogFileName value="true" />
 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
 </layout>
</appender>
</log4net>

Comments

Post a Comment

Popular posts from this blog

#EF : DbEntityValidationException - How can I easily tell what caused the error?

While calling  SaveChanges  on my  DbContext , I get the following exception: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. This is all fine and dandy, but I don't want to attach a debugger every time this exception occurs. More over, in production environments I cannot easily attach a debugger so I have to go to great lengths to reproduce these errors. How can I see the details hidden within the  DbEntityValidationException ? Answer :  The easiest solution is to override SaveChanges on your entities class. You can catch the DbEntityValidationException, unwrap the actual errors and create a new DbEntityValidationException with the improved message. Create a partial class next to your SomethingSomething.Context.cs file. Use the code at the bottom of this post. That's it. Your implementation will automatically use the overriden Save...

#MVC : Why does Html.Label() not work with periods? or Why is @Html.Label() removing some characters

You are misusing the  Html.Label  method. It is for: Returns an HTML label element and the  property name of the property  that is represented by the specified expression. That's why it gets confused if you have a point  .  in the first parameter because it expects a property expression there. However, you can use the second overload: @Html . Label ( "" , String . Format ( "{0}. someText" , 1 )) Or just write out the HTML: <label> @String . Format ( "{0}. someText" , 1 )</ label > or <label class="WelcomeText" style="float: left">Welcome @Html.Label("", Model.USERID + " ( " + Model.ROLE + " )", new { @class = "WelcomeText" })</label>