Click here to Skip to main content
15,860,943 members
Articles / Web Development / ASP.NET

Configuring Log4net inasp.net2.0 and higher Version With Video How Do I?

Rate me:
Please Sign up or sign in to vote.
4.13/5 (12 votes)
28 Oct 2009CPOL7 min read 42K   126   34   13
Configuring Log4net inasp.net2.0 and higher Version With Video How Do I?

   

The Video link For Log4Net How Do I? Down Load is : VideoLinkToHowDoI?[^]
The Video link For Log4Net How Do I? Viewing is : VideoLinkToHowDoI?[^]
  1. It used to work Fine in Local Machine But after Moving it to production .It is always going to error page..!  
  2. But After some modifications in the production ,when entering into database .It is hitting the error page
  3. Wanted to display User Friendly Message but not the  exception for users ..!But Want to store the Exception externally. 

                         The Solution is Log4Net.

  

  EndProduct : 

 

Image 1

                                       Image:LogFile 

Introduction:  

log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary. The log4net package is designed so that log statements can remain in shipped code without incurring ahigh performance cost. It follows that the speed of logging (or rather not logging) is crucial.At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4net is the notion of hierarchical loggers. Using these loggers it is possible to selectively control which log statements are output at arbitrary granularity.

log4net is designed with two distinct goals in mind: speed and flexibility 

Features:

  • Support for multiple frameworks
  • Output to multiple logging targets
  • Hierarchical logging architecture
  • XML Configuration
  • Dynamic Configuration
  • Logging Context
  • Proven architecture
  • Modular and extensible design
  • High performance with flexibility

XML Configuration:

log4net is configured using an XML configuration file. The configuration information can be embedded within other XML configuration files (such as the application's .config file) or in a separate file. The configuration is easily readable and updateable while retaining the flexibility to express all configurations. Alternatively log4net can be configured programmatically.

Dynamic Configuration:

log4net can monitor its configuration file for changes and dynamically apply changes made by the configurator. The logging levels, appenders, layouts, and just about everything else can be adjusted at runtime. In many cases it is possibleto diagnose application issues without terminating the process in question. This can a very valuable tool in investigating issues with deployed applications.

How Do I Log4NetFileAppender: Appends logging events to a file. 

      Start<br />           Run <br />             Devenv //<sub>Fires Up VisualStudio Developers Envoirnment</sub><br />                   File<br />                       NewWebSite <- 

                      Template:Asp.NetWebsite
                      Location:Http http://localhost/Log4netDemo
                      Language:VisualC#
                                                                            OK<--

Add the Following Line in Web.config File.It Will add the Custom ConfigurationSection.To Know More About Custom Configuration

XML
<section name="log4net "type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"> 

Image 2

Adding Custom Configuration Section Image:1

Now Add the appender configuration in the Web.configFile as shown in the following Figure.

Image 3

Appender Section Image:2

XML
<log4net>
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <!-- Please make shure the ..\\Logs directory exists! -->
            <param name="File" value="Logs\\Log4Net.log"/>
            <!--<param name="AppendToFile" value="true"/>-->
            <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
            </layout>
        </appender>
        <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
            <to value=""/>
            <from value=""/>
            <subject value=""/>
            <smtpHost value=""/>
            <bufferSize value="512"/>
            <lossy value="true"/>
            <evaluator type="log4net.Core.LevelEvaluator">
                <threshold value="WARN"/>
            </evaluator>
            <layout type="log4net.Layout.PatternLayout">
<conversionPattern 
       value="%newline%date [%thread] %-5level %logger [%property] - %message%newline%newline%newline"/>
            </layout>
        </appender>
        <logger name="File">
            <level value="All"/>
            <appender-ref ref="LogFileAppender"/>
        </logger>
        <logger name="EmailLog">
            <level value="All"/>
            <appender-ref ref="SmtpAppender"/>
        </logger>
    </log4net> 

Xml Code For Appender Section  

For More Information about File Appender

About File Appender:

Logging events are sent to the file specified by the File property.The file can be opened in either append or overwrite mode by specifying theAppendToFile property. If the file path is relative it is taken as relative from the application base directory. The file encoding can be specified by setting theEncoding property.The layout's Header and Footer values will be written each time the file is opened and closed respectively. If the AppendToFile property is true then the file may contain multiple copies of the header and footer.This appender will first try to open the file for writing when ActivateOptions is called. This will typically be during configuration. If the file cannot be opened for writing the appender will attempt to open the file again each time a message is logged to the appender. If the file cannot be opened for writing when a message is logged then the message will be discarded by this appender.

The FileAppender supports pluggable file locking models via the Locking Model property. The default behavior, implemented by FileAppender.ExclusiveLock is to obtain an exclusive write lock on the file until this appender is closed. Thealternative model, FileAppender.MinimalLock, only holds a write lock while the appender is writing a logging event.

Global.asax File :

The Global.asax file, also known as the ASP.NET application file, is an optional filethat contains code for responding to application-level events raised by ASP.NET or by HttpModules. The Global.asax file resides in the root directory of anASP.NET-based application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the Http Application base class. The Global.asax file itself is configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it.

Adding a Global.asax File:

<code><code><code><code><code><code><code><code><code>

       Alt+Ctrl+L (opens SolutionExplorer) <br />               AddNewItem <br />                   GlobalApplicationClass

                Name :Global.asax

                Language :VisualC# 

                                                                 Add<-

Adds a Global.asax File in the Website.

Image 4

Adding a Global.asax File Image :3

Now Add the Reference of the Log4net Dll as shown in the following figure.

      Alt+Ctrl+L (opens SolutionExplorer)<br />                     AddReference<br />                       Browse(Browse and Select the dll)

                                             OK<- <br />

Image 5

Adding Reference Of Log4Net Image :4

Add the Following line in the Application_Start event as Shown Below 

Image 6

Adding XmlConfigurator Image :5  

C#
void Application_Start(object sender, EventArgs e)
     {
      // Code that runs on application startup
      log4net.Config.XmlConfigurator.Configure();
      } 

The Above Line instructs the XmlConfigurator to parse a configuration file and set up logging accordingly. The path to the configuration file is specified on the  command line.

Application_Start event: Code that runs on application startup 

Now Add the Following Code in Default.aspx Page_Load Event

C#
   //Typer of messages Which Log4net Supports..!
log4net.ILog logger = log4net.LogManager.GetLogger("File");
logger.Info("This  is For Info Message");
logger.Warn("This is For Warn Message");
logger.Error("This is For Error Message");
logger.Debug("this is for Debug Message");

Image 7

Code In Default.aspx.cs Image:6

 

 Ilog : 

         The ILog interface is use by application to log messages into the log4net framework.  

Ilog Properties :   

Image 8IsDebugEnabledChecks if this logger is enabled for the Debug level.
Image 9IsErrorEnabledChecks if this logger is enabled for the Error level.
Image 10IsFatalEnabledChecks if this logger is enabled for the Fatal level.
Image 11IsInfoEnabledChecks if this logger is enabled for the Info level.
Image 12IsWarnEnabledChecks if this logger is enabled for the Warn level.

Public Instance Methods Of ILog:  

Image 13DebugOverloaded. Log a message object with the Debug level.
Image 14DebugFormatOverloaded. Log a formatted string with the Debug level.
Image 15ErrorOverloaded. Log a message object with the Error level.
Image 16ErrorFormatOverloaded. Log a formatted message string with the Errorlevel.
Image 17FatalOverloaded. Log a message object with the Fatal level.
Image 18FatalFormatOverloaded. Log a formatted message string with the Fatallevel.
Image 19InfoOverloaded. Log a message object with the Info level.
Image 20InfoFormatOverloaded. Log a formatted message string with the Infolevel.
Image 21WarnOverloaded. Log a message object with the Warn level.
Image 22WarnFormat Overloaded. Log a formatted message string with the Warn

LogManager:

This class has static methods that are used by a client to request a logger instance. The GetLogger method is used to retrieve a logger. For More Information on LogManager

They are many other ways to do for log4net..! For More Information on Log4net Types

 Now Run The File You Will See a New Folder Logs in the Solution Explorer as Shown Below.  

 

Image 23

Logs Folder In Solution Explorer Image:7  

Note :

       If Still Didn't  Work Please check the IIs Settings for the website .Make Sure that You gave the Write authority to the folder Logs.   

Extra Features(Optional) :   

    You can Log the server last error in the logger file by using the Application_Error  in Global.asax file . 

C#
void Application_Error(object sender, EventArgs e)
    {
       log4net.ILog logger = log4net.LogManager.GetLogger("File");
       string error = Server.GetLastError().GetBaseException().ToString();
       logger.Error(error);

    }

Summary : 

         The Above article helps You to log the background details of the application  using log4net file appender. 

Reference and Further Study : 

  • Updated on 14 October 2009  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRegarding SMTP Configuration Pin
Pushkarr14-Jul-10 21:04
Pushkarr14-Jul-10 21:04 
GeneralNice article but unable to view the vedio Pin
nainakarri25-Nov-09 0:44
nainakarri25-Nov-09 0:44 
GeneralRe: Nice article but unable to view the vedio [modified] Pin
sashidhar25-Nov-09 0:51
sashidhar25-Nov-09 0:51 
GeneralMy vote of 1 Pin
Corey Fournier28-Oct-09 2:46
Corey Fournier28-Oct-09 2:46 
Generalbvnm Pin
Jamindar12327-Oct-09 5:15
Jamindar12327-Oct-09 5:15 
GeneralRe: Nice One Pin
sashidhar27-Oct-09 5:18
sashidhar27-Oct-09 5:18 
GeneralMy vote of 2 Pin
Mukesh_B27-Oct-09 0:46
Mukesh_B27-Oct-09 0:46 
GeneralRe: My vote of 2 Pin
Corey Fournier28-Oct-09 2:45
Corey Fournier28-Oct-09 2:45 
QuestionHow can I configure logNet to write to CommonApplication Data? Pin
devnet24722-Oct-09 19:25
devnet24722-Oct-09 19:25 
AnswerRe: How can I configure logNet to write to CommonApplication Data? Pin
sashidhar22-Oct-09 19:40
sashidhar22-Oct-09 19:40 
GeneralRe: How can I configure logNet to write to CommonApplication Data? Pin
devnet24722-Oct-09 22:15
devnet24722-Oct-09 22:15 
GeneralRe: How can I configure logNet to write to CommonApplication Data? Pin
sashidhar22-Oct-09 22:23
sashidhar22-Oct-09 22:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.