For logging service my choice is log4net from Apache Software Foundation. It is easy to use, open source and well documented. There are also so many logging services but they are not open source. So it is an easy and best solution for you.
Write Log in Console procedures are given below-
1. Download log4net from http://logging.apache.org/log4net/download.html
2. Open visual studio and create a new console application.
3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.
4. write the main method like this
using System; using System.Collections.Generic; using System.Text; using log4net; using log4net.Config; namespace LogPractice { class Program { void Main(string[] args) { log4net.Config.BasicConfigurator.Configure(); log4net.ILog log = log4net.LogManager.GetLogger(Program); log.Debug("THis is sadi's world!"); log.Info("How beautyful the console looks like"); log.Warn("You are great you did this"); log.Error("Who make you know is the best"); log.Fatal("sadi the great"); Console.ReadLine(); // Hold the output } } }
Using Log4net Write log in a file, Procedures are given below-
1. Download log4net from http://logging.apache.org/log4net/download.html
2. Open visual studio and create an application.
3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.
4. Now put this web.config/app.config file in configuration tag.
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections> <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>
this configuration creates a log file in C:\temp\log.txt.
5. To use log4net put this as a local class variable: protected static readonly ILog log =
LogManager.GetLogger(Program);
6. And do this to write messages in the log file. log.Debug(“this text will be in log file”);
For Example:
using System; using System.Collections.Generic; using System.Text; using log4net; using log4net.Config; namespace <code>LogPractice</code> { class Program { protected static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); //————————– log.Warn("sadi the great"); } } }
7. Compile and run the application, and you’ll see output to the console
N.B : if you run this code log will show in the c:/temp/log.txt file.
You are awesome. I read same kind of articles in as many as 7 websites.
I felt something different when i went thru ur webpage. Ah! I was right I got the log4net working… cool
Your way of telling about how to use log 4net is really awesome…
i visited more than 10 pages about how to use log4net but your page did the trick….
There are millions of examples of how to use log4net with a file appended. Why can you not give an example of how to log with a database?
thanks for ur comment Lee. I was little bit busy with my task.But i posted how to store log in database using log4net.
you can view my new post
https://sadi02.wordpress.com/2008/09/15/how-to-store-log-in-database-using-log4net/
cheers
Thanks, and I have a question –> My app need to write 2 log files, one for success message, one for failure message, what should I do?
And idea?
Hi james,
Sorry for being late reply. I think you can solve this problem by creating a log service that can help you in a very sophisticated way. You can also use log4net and use the log level. You can show your success message by info and failure message by error level then you need not to create another log file.
Thanks!
Hopefully you’ve solved your problem by now but there is a fairly simple way to solve this problem by using two separate loggers.
Instead of just having one “ILog log = LogManager.GetLogger(typeof(Program));” statement you could just have a successLog and a failLog:
ILog successLog = LogManager.GetLogger(typeof(Program)+”.Success”);
(fit to whatever your logger naming scheme is)
Seems too easy to forget that you can easily have multiple loggers within a single class just because you get used to having a single static logger defined per class.
Nice work. Found this after a long search and numerous other examples that did not work.
cheers
Excellent Tutotial about log4net!
Good.I feel that this is easy understandable and work fine and good example.Keep it up.
I am new to Log4Net and have visited so many sites to find step by step tutorial to understand it and make it working but was disappointed. When I read your article and tries to implement LOG4NET it worked. Thanks a lot.
hey it’s great……….i done with help of you websit….
Your article didn’t work, I got errors…
Send the error
if I can help you in any way ..
-Author
Excellent article! just started using directly.
thanks a lot.
Vinov
Very simple and nice article for quick start.
how can i change the file location in code? does log4net support it?
Hi Jack,
obviously log4net supports this. you can dinamicaly change file location path using log4net. The following post might help you …
http://stackoverflow.com/questions/1535736/log4net-how-can-i-change-the-file-location-programmatically-c
Thanks!!!
Man..you are great…it helped me a lot…
thanks nice and simple
Didn’t work. I got a “Missing Attribute value on ‘ref’. And 26 “Could not find scheme information for the element ‘…'” I am using Visual Studio 2010 Beta 2.
Sorry, I fixed my last problem. I didn’t add using log4net.Config. Now, the file does not create. I am running Windows 7. Maybe something wrong with permissions?
I tried to write an log.Info(“…”); to a log.txt, but the file is not even created. I am running Windows 7. So maybe file permissions are an issue? Some help would be appreciated.
Hi Mohit,
Recently windows 7 is unavailable to me. If I can manage definitely I will try to help you..
Thanks!!!
Try setting , not
Try setting [level value=”ALL” /] not [level value=”DEBUG” /]
I’ll test it.Thanks u.
Hi Sadi,
I have an application which is using 5 threads and all are running simultaneously. I need to write into a single log file whenever any of the thread is failing and also it should write into log file once the thread is completed successfully. Do you have any example programs for this?
I think you can use log4net for doing this. Log4net has the flexibility to doing this.
unfortunately I have not written down any program which can help you in this matter.
In My solution(Program) I have used my built in logging service. This is not very hard to build.
Great way of explaining things. However, I am not technical savvy and am in a dire need of some help. I would appreciate if you could provide some assistance/ guidance
We are looking into setting up a custom messaging alert system (business and system related messages) to be logged in a custom Oracle table (to be created) and forward those automatically with an option of sending them via email, IM, or text. These messages might come from web or client based applications. Once alert message is created and sent we would like to use the same oracle table and build some kind of dashboard (web or client)
I would appreciate any help in this regard.
Thank you
Roan
Hi Ron,
Please first try to plan how do we want to use log4net.
Thanks.. really useful…
I am getting the following 2 errors when trying to compile:
log4Net.Config.XmlConfigurator.Configure();
The name ‘log4Net’ does not exist in the current context
protected static readonly ILog log = LogManager.GetLogger(typeof(Program));
The type or namespace name ‘Program’ could not be found (are you missing a using directive or an assembly reference?)
Can you help?
Hey, Program is the class name. Your class name is Program?
You can also use the below statement:-
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
This will automatically point to current class.
Late, but still useful for others:
In the binary file you download from log4net page, it also appears a “net-cp” folder… Those files are designed for Client Profile projects (which may be yours). That will just do. Good luck!
saddasadsdasas
TIMMY!!!!!
One doubt ?
What ever method of getlogger object we are using will go to log file ?
I mean all the below strings are will write into the log file ?
log.Debug(“THis is sadi’s world!”);
log.Info(“How beautyful the console looks like”);
log.Warn(“You are great you did this”);
log.Error(“Who make you know is the best”);
log.Fatal(“sadi the great”);
Or any difference is in this method ? (Like log.Error can be used only when error is throwing ..etc..)
Please clarify ?
Hi Menon,
These 5 types are used to identify the type of error occurred in your application just by seeing the log file. You can use appropriate methods whereever you feel that is required.
The log will have the error type as prefix (eg. Debug or Warn)
Also you can restrict the type of error to be logged by using the below tag inside the Root tag.
ErrorTypes can be:
“All” — All the errors will be logged
“Debug” — From Debug to Fatal (same as like “All”)
“Info” — From Info to Fatal (except Debug)
“Warn” — From Warn to Fatal (except Debug and Info)
“Error” — Only Error and Fatal
“Fatal” — Only Fatal errors will be logged.
tag:
<>
[level value=”ALL” /]
Great example, thanks.
Question: For an asp.net app, do I need to put
in every Page_Load?
Is it possible to execute this once for the whole app?
Try configuring it in Global.asax in Application_Start http://aspalliance.com/1114_Understanding_the_Globalasax_file.all
You wouldn’t need to set this up in every aspx page.
That makes sense. I created a Global.cs and added
public class Global : System.Web.HttpApplication
{
protected static readonly ILog log = LogManager.GetLogger(typeof(Global));
void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
log.Info("*** APPLICATION STARTED ***");
}
}
I faced several issues with this simple task. I had to use XmlConfigurator to get it working instead of BasicConfigurator as BasicConfigurator is obsolete. Version of log4net is 1.2.10.0.
Thanks for the example. Its helping me get started :).
Sadi,
I am new to logging and trying to use log4net in the wpf web browser application to write log in a file. I dont get an error message but log file is not generated.
Thanks in advance for your help.
Hi,
I m creating an application in MVC, I m new to log4net, i want to create a log of what actions are slowing us down for the whole site and let those events build up for 2-3 days. Then group by action, and get an average time to process, and see what the major issues are in the application. and i have no idea how to achieve this, will u please help me on this. I have implemented you code in my app and it is creating log file successfully, but i m not sure how to find out the exact time taken by each event/action.
Please reply soon….
Thanks for the example and q&a. They are great help for me to implement the log in my application.
I faced two problems:
1. There are some message that we want to put into log no matter what level it is. Is there a way to do it?
2. Our application allows user to change log evel during runtime. Therefore, we add the log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(SpecialDirectories.OptionsDotConfig)) if there is any change in the log level. But it creates new log file everytime. Is it possible to keep writing to the same log file?
Best Regards,
SJC
Hey, You resolved it?
No clue how to do it yet. Any suggestion?
Hi!!! i am doing what you said but when I execute this line:
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(“app.config”));
I get this error:
Value cannot be null.
Parameter name: address
and I get it too if I use the AssemblyInfo.
my app.config file is:
thank you!!!!!!!!
Excellent tutorial. Got me up and running. I was struggling the official log4net documentation! Good job!
Hi,
Won’t mind if someone gives me a quick tip on how to configure log4net to log INFO to FileSystem (only) and ERROR & FATAL to File, DB and Email.
At the moment, I set threshold value to ERROR for my AdoNetAppender & SmtpAppender, INFO to my LogFileAppender and no level value to my . It sends both INFO to my FileSystem and DB and sends ERROR to all 3. I want to prevent INFO from going into the DB.
Thanks.
For some reason, Line 6 of my prev post didn’t come out properly. It should read
.. SmtpAppender, INFO to my LogFileAppender and no level value to my root. It sends both …
Hi Sadi,
can I have multiple log file running for an application as it is required to log error and success parameters in different files
can you please tel me the configuration for this?
Hi Ahmed,
Your question was similar to mine. I’ve been able to resolve it. Let me know if you still need assistance, so I can publish the steps I took.
Cheers.
Kwex, Can you provide the steps.
Thanks
Anand
Hi, Nice article. Unfortunately I dont have Visual Studio. Can you please advice how can I load the dll in aspx.cs file. Any pointer will be helpful.
regards
Awesome content! Thank you!
gilbert realtor
Hi,
I’ve written below line of code:
log4net.Config.XmlConfigurator.Configure(configFile);
log4net.Appender.IAppender[] aps = log4net.LogManager.GetRepository().GetAppenders();
but aps.count is returning as “0”. I have added following code in a seperate app.config file:
I saw a lot of examples, but urs one realy works.- Thanks
This is excellent………… but i want to read the app.xml file into a dataset and i want to show this in a gridview. Is this possible? If possible please let me know the example.
This is excellent………… but i want to read the app.xml file into a dataset and i want to show this in a gridview. Is this possible? If possible please let me know the example.
If you’re working with Visual Studio 2010 default setup you’ll probably get the error: The name ‘log4Net’ does not exist in the current context.
The reason is that your target framework is “.Net Framework 4 Client profile”.
Right click your project -> properties ->change target framework to “.Net Framework 4”
Good luck
Fred
Hey Fred – I spent a whole day tearing my hair out trying to get log4net working with VS2010. I just tried you suggestion and it works !!
Excellent -I have absolutely no idea why it works but it does.
Inner harmony is now restored – Many many thanks
Bob
thanks, worked 😀
Hi,
Fred Verbeke, I was also expericing this error when compiling my solution.
Your suggestion fixed my problem!
Cheers
If you are authorized to work in the US without requiring sponsorship see my profile for an opportunity.
Pingback: links for 2011-02-24 - Craig's Blog
Hi..
I tried your example.I think keping configuration information in separate xml is more beneficial rather than in app/web.config.Earlier i got problem while logging in release mode while it was working file in debug mode.
Keeping it separate helped me.
Thanks again
I did as is above and I am getting the following error;
Unrecognized configuration section log4net
@Fred Verbeke
Thanks! That just tripped me up for 30 minutes.
Nice Article…
After uninstall (web application) log folder not removed. This folder have empty log file. What should I do to remove this log file?
Great article ! first time i got it to work 😛 thanks 😛
hey i am new to .net. i want to write a code that will create logfile on daily basis. how do i do that??
Pingback: log4net – write log in a file « Vijay Mahankali
Hi,
I am using log4net, how can i fix/restrict the log file size by removing old log.It would be nice if i could take backup of these files.
thanks
by fix i mean limit the size of log file
the logging to file part doesn’t seem to work for me… does anybody else get this:
Could not find schema information for the element ‘log4net’.
Could not find schema information for the element ‘root’.
Could not find schema information for the element ‘level’.
..
..
The program runs, it just seems to do nothing.
Hello,
I followed the example for a console application but i get this error:
The type initializer for ‘XXXXX’ threw an exception.
Any ideas what could I be doing wrong?
Thanks!
Muchas gracias, muy sencilla y clara la explicación; trabaja sin problemas!
5. To use log4net put this as a local class variable: protected static readonly ILog log =
LogManager.GetLogger(Program);
should be
(typeof(Program)) instead of (Program)
Thank you for your warning. Otherwise, my code will not run.
Good job man.
Thanks for sharing this example.
~Jimmy.
Good article.
but I found the log.txt is not created, untill I change the configure line to be
log4net.Config.DOMConfigurator.Configure();
Can you explain the difference between them?
Thanks in advance!
Hi,
I am using above logging method as it was working fine till I was debugging. When I finally made the application as Windows Service, the program itself is working as its performs what is should do, but it is not logging anything…..
I have added the assembly line as mentioned on different websites.
Regards
Hassan
thx. helped me too 🙂
One line of code is worth thousand lines of explaination.
Thanks a lot,
Jay
Pingback: Exception Handling in ASP.NET MVC 3– Follow up « KK's bytes
Very cool and without any redundant comments and analysis. Code speaks for itself! 🙂
Hi, the file will not create after I publish my console app. It works perfect on dev server. I can’t even get the trace file to work.. I’m using Windows 7, have given IIS_WPG full access to folder and have tried to set the
Any ideas?
Thanks
I used to be recommended this blog through my cousin. I’m now not positive whether this post is written by way of him as no one else recognise such specified about my trouble. You are wonderful! Thanks!
i am using Log4net.ddl in the web serivce to get log,but i can able to get log on the location below my code: in wwb config:
…..
……..
……..
in c.s page:
class Logger
{
private static ILog _log = LogManager.GetLogger(typeof(Logger));
……
…
static Logger()
{
ReInitialise();
}
public static void ReInitialise()
{
LogManager.ShutdownRepository();
LogManager.ResetConfiguration();
try
{
log4net.Config.XmlConfigurator.Configure();
}
…
but i am not getting the log file..
This really helped me get started without any issue..thanks a bunch, Sadi!
Hi,
I need to create a logfile for my application. So I am following your way of approach.
But I am not stuck in mind as not able to find log4net.dll in downlaoded folder to add the reference.
You would need to download and build in Visual Studio to get the Dlls. Try this direct link http://apache.mirror.rbftpnetworks.com//logging/log4net/source/log4net-1.2.11-src.zip. Open the solution in the “src” folder – log4net.vs2010.sln or log4net.vs2008.sln (depending on what Visual Studio you have installed) and build it.
It would generate the dll you need to reference in your project. Let me know if you have difficulties doing it.
Cheers.
I have two appenders in my app.config for a .net C# application. One is for a database log and the other for a rolling file appender. I need to use these two appenders but with a different message parameter to each one. I therefore cannot just use one log.info call but I need to instantiate two ILog objects, each one connected to a different appender from my app.config. Is this possible?
Thanks for any help you can offer.
Why log4net has ALL and DEBUG, as they both do the same thing? There should some reason they created two levels with same functionality.
Appreciate the reply.
Hi,
I’m stuck @ Using Log4net Write log in a file.
I made a the app.config file (add,new item,application configuration file) and copied your code in it, now it gives me 3 errors:
1.)XML document cannot contain multiple root level elements.
2.)The “log4net” element is not declared
3.) Application Configuration file “App.config” is invalid. There are multiple root elements. Line 4, position 2.
Also “Write Log in Console” did not work for me:
Program ‘D:\Visual Studio 2010\Projects\O2PROG\Logger\obj\x86\Debug\Logger.exe’ does not contain a static ‘Main’ method suitable for an entry point Logger
Copied exact code:
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;
namespace LogPractice
{
class Program
{
void Main(string[] args)
{
log4net.Config.BasicConfigurator.Configure();
log4net.ILog log = LogManager.GetLogger(typeof(Program));
log.Debug(“THis is sadi’s world!”);
log.Info(“How beautyful the console looks like”);
log.Warn(“You are great you did this”);
log.Error(“Who make you know is the best”);
log.Fatal(“sadi the great”);
Console.ReadLine(); // Hold the output
}
}
}
Greets,
Dubzzz
Fixed with
Thank you, I’v been compiling different guides and tutorials, yours made the final touch.
I appreciate the effort.
Such a nice work!
But, many people faced similar problems as you see.
Could you update your article for the current version of log4net?
I follow up the log4net settings by doing copy/paste then i have a error message it’s not well configured.
Great tutorial. Just one following correction:
log =
LogManager.GetLogger(Program);
should be
(typeof(Program)) instead of (Program)
Hi! Generally we are not interested to show any type of application error to end user. Error logs are very important for collecting all error data generated by an application. It is more useful during an early or beta release of a product. That’s why it is better to store any kind of exceptions in one place. This files can be send by email or others technology to developer. Time to time developer must analyze them and fix all the bugs without knowing clients. It will increase application performance. So thanks for sharing your knowledge.
This is a good tip particularly to those fresh to the blogosphere. Short but very accurate info… Appreciate your sharing this one. A must read article!
Good Blog It solved my Problem. I have one Issue How to Login User ID through the Log4Net ….Is there any way?
I like the helpful info you supply on your articles. I’ll bookmark your blog and take a look at again right here regularly. I am fairly sure I’ll be told a lot of new stuff proper right here! Good luck for the next!
Needed to post you that little bit of note to finally say thank you the moment again for the pleasing guidelines you have provided here. This is so remarkably generous with you to deliver publicly what exactly some people could possibly have advertised as an electronic book to make some money on their own, most notably considering that you might well have tried it in case you considered necessary. The thoughts also acted to be a easy way to be aware that most people have a similar zeal just as my very own to learn more and more in regard to this problem. I am certain there are thousands of more pleasant situations up front for people who find out your site.
How to create the common library(dll) for Error logging using log4net. That dll will be implemented may application