Click here to Skip to main content
Click here to Skip to main content

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

, 28 Oct 2009
Rate this:
Please Sign up or sign in to vote.
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: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
           Run 
             Devenv //<sub>Fires Up VisualStudio Developers Envoirnment</sub>
                   File
                       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

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

Adding Custom Configuration Section Image:1

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

Appender Section Image:2

<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:

       Alt+Ctrl+L (opens SolutionExplorer) 
               AddNewItem  
                   GlobalApplicationClass 

                Name :Global.asax

                Language :VisualC# 

                                                                 Add<-

Adds a Global.asax File in the Website.

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)
                     AddReference
                       Browse(Browse and Select the dll)

                                             OK<- 
                                                                                               

Adding Reference Of Log4Net Image :4

Add the Following line in the Application_Start event as Shown Below 

Adding XmlConfigurator Image :5  

                       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

           //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");

Code In Default.aspx.cs Image:6

 

 Ilog : 

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

Ilog Properties :   

IsDebugEnabledChecks if this logger is enabled for the Debug level.
IsErrorEnabledChecks if this logger is enabled for the Error level.
IsFatalEnabledChecks if this logger is enabled for the Fatal level.
IsInfoEnabledChecks if this logger is enabled for the Info level.
IsWarnEnabledChecks if this logger is enabled for the Warn level.

Public Instance Methods Of ILog:  

DebugOverloaded. Log a message object with the Debug level.
DebugFormatOverloaded. Log a formatted string with the Debug level.
ErrorOverloaded. Log a message object with the Error level.
ErrorFormatOverloaded. Log a formatted message string with the Errorlevel.
FatalOverloaded. Log a message object with the Fatal level.
FatalFormatOverloaded. Log a formatted message string with the Fatallevel.
InfoOverloaded. Log a message object with the Info level.
InfoFormatOverloaded. Log a formatted message string with the Infolevel.
WarnOverloaded. Log a message object with the Warn level.
WarnFormat 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.  

 

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 . 

            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)

About the Author

sashidhar
Software Developer
India India
No Biography provided

Comments and Discussions

 
GeneralRegarding SMTP Configuration PinmemberPushkarr14-Jul-10 21:04 
GeneralNice article but unable to view the vedio Pinmembernainakarri25-Nov-09 0:44 
GeneralRe: Nice article but unable to view the vedio [modified] Pinmembersashidhar25-Nov-09 0:51 
GeneralMy vote of 1 PinmemberCorey Fournier28-Oct-09 2:46 
Generalbvnm PinmemberJamindar12327-Oct-09 5:15 
xn
GeneralRe: Nice One Pinmembersashidhar27-Oct-09 5:18 
GeneralMy vote of 2 PinmemberMukesh_B27-Oct-09 0:46 
GeneralRe: My vote of 2 PinmemberCorey Fournier28-Oct-09 2:45 
QuestionHow can I configure logNet to write to CommonApplication Data? Pinmemberdevnet24722-Oct-09 19:25 
AnswerRe: How can I configure logNet to write to CommonApplication Data? Pinmembersashidhar22-Oct-09 19:40 
GeneralRe: How can I configure logNet to write to CommonApplication Data? Pinmemberdevnet24722-Oct-09 22:15 
GeneralRe: How can I configure logNet to write to CommonApplication Data? Pinmembersashidhar22-Oct-09 22:23 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 28 Oct 2009
Article Copyright 2009 by sashidhar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid