Sie sind auf Seite 1von 40

Log4Net Tutorial in C# .

net (How can I show log in a file?)


Posted on June 29, 2008 by Md Shaik Sadi
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
.Colle
ctions
.Gener
ic;

using Sy
stem.Te
xt;

using lo
g4net;

using log4
net.Confi
g;

namespace 
LogPracti
ce

  cla
ss Pro
gram

  {

1     void Main(
1 string[] args)

1
    {
2

     log4net.Config.BasicConfig
urator.Configure();

     log4net.ILog log =
log4net.LogManager.GetLogger(P
rogram);

log.Debug("THis
15 is sadi's
world!");

     log.Info("Ho
w beautyful the
16
console looks
like");

     log.Warn("You are
17
great you did this");

18      log.Error("Who
make you know is the
best");

     log.Fatal("s
adi the great");

     Console.Read
Line();  // 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.

<configSe
ctions>

  <sectio
n name="lo
g4net" typ
e="log4ne
t.Config.
Log4NetCo
nfigurati
onSection
Handler,L
og4net"/>

</confi
gSectio
ns>

<log4n
et>
<
r
o
o
t
>

 
<
l
e
v
e

v
a
l
u
e
=
"
D
E
B
U
G

/
>

0  <appender-ref ref="L
7 ogFileAppender" />

0
</root>
8

0 <appender name="LogFileAppender" type="log4net.Appen
9 der.RollingFileAppender" >

 <param name="File" value="C:\Try\logger\logger
10
\bin\Debug\log.txt" />

 <param name="AppendToFile
" value="true" />

 <rollingStyle value="Size
" />

 <maxSizeRollBackup
s value="10" />

 <maximumFileSize v
alue="10MB" />

 <staticLogFileName v
alue="true" />

 <layout type="log4ne
t.Layout.PatternLayo
ut">

 <param name="ConversionPattern" value="%-5p
17
%d{yyyy-MM-dd hh:mm:ss} – %m%n" />

18  </layout>

</a
ppe
nde
r>

</
lo
g4
ne
t>

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
.Colle
ctions
.Gener
ic;

using Sy
stem.Te
xt;

using lo
g4net;

using log4
net.Confi
g;

namespace <code>Log
Practice</code>

 cla
ss Pr
ogra
m

 {
11  protected static readonly ILog log =
LogManager.GetLogger(typeof(Program));

12  static void Main(string[] args)

 log4net.Config.XmlConfigu
rator.Configure();

 //————————–

 log.Warn("s
1
adi the
7
great");

1
 }
8

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.

 
 
21 Votes
Ads by Google
Juniper VPN Solutions
Juniper Networks Official Site. Find Your Business Solution Now.
www.Juniper.net
About Md Shaik Sadi
I am Md. Shaik Sadi. I have worked on different phases of software development life cycle. I have got
my B.Sc.(Engg) degree in COmputer Science and Engineering and started my carrer as a trainee
developer. Recently I am working on asp.net/2 and want to stablish my career on this platfrom.
View all posts by Md Shaik Sadi →

This entry was posted in Computer Science and tagged Basic Programming, C#.Net, Computer Science, OOP.


Bookmark the permalink.

← What is the main difference between process and procedure in Software Engineering?


ADO.NET – DataReader(Connected) and DataSet(Disconnected) in C# .Net with Examples →

Like
Be the first to like this post.
62 Responses to Log4Net Tutorial in C# .net (How can I show log
in a file?)

1. Prabhakar Kasi says:
July 6, 2008 at 2:05 am

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
Reply

2. Himanshu says:
August 26, 2008 at 7:47 am

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….
Reply

3. Lee says:
September 1, 2008 at 11:01 am
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?
Reply

4. Md. Shaik Sadi says:


September 15, 2008 at 10:22 am

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


http://sadi02.wordpress.com/2008/09/15/how-to-store-log-in-database-using-
log4net/
cheers
Reply

5. James Yeh says:
October 24, 2008 at 6:18 am

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?
Reply

o Md. Shaik Sadi says:


January 19, 2010 at 1:55 am

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!
Reply
o Nick V says:
February 4, 2010 at 3:14 pm

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.
Reply

6. Benjy says:
January 2, 2009 at 10:49 pm

Nice work. Found this after a long search and numerous other examples that did not
work.

cheers
Reply

7. Muhammad Asif says:
January 13, 2009 at 10:30 am

Excellent Tutotial about log4net!


Reply

8. Arunkumar says:
June 16, 2009 at 10:31 am

Good.I feel that this is easy understandable and work fine and good example.Keep it up.
Reply

9. Manjeet says:
June 18, 2009 at 1:35 am

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.
Reply

10. jignesh says:
June 23, 2009 at 5:09 am

hey it’s great……….i done with help of you websit….


Reply

11. MichaelL says:
July 17, 2009 at 4:07 pm

Your article didn’t work, I got errors…


Reply

12. Md. Shaik Sadi says:


July 20, 2009 at 11:54 am

Send the error


if I can help you in any way ..

-Author
Reply

13. vinov says:
July 23, 2009 at 2:05 pm

Excellent article! just started using directly.


thanks a lot.
Vinov
Reply

14. Nazish Kanwal says:


September 7, 2009 at 4:35 am

Very simple and nice article for quick start.


Reply

15. Jack says:
September 15, 2009 at 12:43 am

how can i change the file location in code? does log4net support it?
Reply

o Md. Shaik Sadi says:


January 19, 2010 at 4:19 am

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!!!
Reply

16. Foyzul Karim says:


September 29, 2009 at 2:45 pm

Man..you are great…it helped me a lot…


Reply

17. yang says:
December 14, 2009 at 7:29 am
thanks nice and simple
Reply

18. Mohit Deshpande says:


January 7, 2010 at 1:42 am

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.
Reply

19. Mohit Deshpande says:


January 7, 2010 at 1:49 am

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?
Reply

20. Mohit Deshpande says:


January 7, 2010 at 10:21 pm

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.
Reply

o Md. Shaik Sadi says:


January 19, 2010 at 4:24 am

Hi Mohit,

Recently windows 7 is unavailable to me. If I can manage definitely I will try to help
you..

Thanks!!!
Reply
o Vladimir says:
February 24, 2010 at 4:41 pm

Try setting , not


Reply

 Vladimir says:
February 24, 2010 at 4:42 pm

Try setting [level value="ALL" /] not [level value="DEBUG" /]

21. ShweNanThu says:
January 18, 2010 at 9:22 am

I’ll test it.Thanks u.


Reply

22. Sivakumar says:
January 29, 2010 at 5:07 pm

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?
Reply

o Md. Shaik Sadi says:


February 4, 2010 at 2:25 am

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.
Reply
23. Ron says:
January 29, 2010 at 6:52 pm

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
Reply

o Md. Shaik Sadi says:


February 4, 2010 at 2:27 am

Hi Ron,
Please first try to plan how do we want to use log4net.
Reply

24. James says:
January 30, 2010 at 10:47 am

Thanks.. really useful…


Reply

25. Lynn says:
February 18, 2010 at 2:55 pm
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?


Reply

o Sivakumar says:
March 11, 2010 at 6:53 am

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().Declaring
Type);

This will automatically point to current class.


Reply

26. as says:
February 23, 2010 at 9:18 am

saddasadsdasas
Reply

27. NK Menon says:
February 23, 2010 at 6:06 pm

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 ?
Reply

o Sivakumar says:
March 11, 2010 at 7:41 am

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.
Reply

 Sivakumar says:
March 11, 2010 at 7:46 am

tag:

 Sivakumar says:
March 11, 2010 at 7:46 am

<>

28. Sivakumar says:
March 11, 2010 at 7:47 am

[level value="ALL" /]
Reply

29. Scott says:
March 30, 2010 at 8:31 pm

Great example, thanks.

Question: For an asp.net app, do I need to put

log4net.Config.XmlConfigurator.Configure();

in every Page_Load?
Is it possible to execute this once for the whole app?
Reply

o Ram says:
April 12, 2010 at 2:00 pm
Try configuring it in Global.asax in
Application_Starthttp://aspalliance.com/1114_Understanding_the_Globalasax_file.all
You wouldn’t need to set this up in every aspx page.
Reply

 Scott says:
April 16, 2010 at 5:08 pm

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 ***");
}

30. Rajesh says:
May 5, 2010 at 9:03 am

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.
Reply

31. Ryan says:
May 24, 2010 at 6:59 pm

Thanks for the example. Its helping me get started   .


Reply
32. Ravi says:
June 12, 2010 at 4:31 am

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.


Reply

33. Anil D says:


June 18, 2010 at 12:46 pm

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….


Reply

34. SJC says:
June 25, 2010 at 5:30 pm

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
Reply

o Sivakumar says:
July 5, 2010 at 11:40 am

Hey, You resolved it?


Reply

 SJC says:
August 17, 2010 at 7:59 pm

No clue how to do it yet. Any suggestion?

35. Nicole says:
July 1, 2010 at 7:44 pm

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!!!!!!!!
Reply

36. Robert says:
July 16, 2010 at 9:13 pm

Excellent tutorial. Got me up and running. I was struggling the official log4net
documentation! Good job!
Reply

37. Kwex says:
July 29, 2010 at 8:59 am

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.
Reply

38. Kwex says:
July 29, 2010 at 9:02 am

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 …
Reply

39. Ahmed says:
August 4, 2010 at 9:48 am

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?


Reply

o Kwex says:
August 17, 2010 at 8:14 am

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.
Reply

40. Vijay Srivastava says:


August 12, 2010 at 11:48 am

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
Reply

41. chandler realtor says:


August 24, 2010 at 9:04 pm

Awesome content! Thank you!

gilbert realtor
Reply

42. Sima Agrawal says:


September 7, 2010 at 4:09 am
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:
Reply

43. kapil says:
September 13, 2010 at 9:11 pm

I saw a lot of examples, but urs one realy works.- Thanks


Reply

44. Satya says:
November 3, 2010 at 8:01 am

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.
Reply

45. Satish says:
November 3, 2010 at 8:02 am

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.
Reply
Leave a Reply
Your email address will not be published. Required fields are marked *
Name *
Email *
Website
Comment
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b>
<blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Comment

 Notify me of follow-up comments via email.


 Subscribe to this site by email
How to store log in database using log4net
Posted on September 15, 2008 by Md Shaik Sadi
One of the best ways to store log in the database using log4net coz it is easy to use and its world wide popularity.
For storing log in the database all task are manage by log4net internally.
At first you need to create a table for Storing log in the SqlServer database
The table should be like as
CREATE TABLE [dbo].[Log] (
    [Id] [int] IDENTITY (1, 1) NOT NULL,
    [Date] [datetime] NOT NULL,
    [Thread] [varchar] (255) NOT NULL,
    [Level] [varchar] (50) NOT NULL,
    [Logger] [varchar] (255) NOT NULL,
    [Message] [varchar] (4000) NOT NULL,
    [Exception] [varchar] (2000) NULL
)

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.

0 <configSections>
1 <section name="log4net"type="log4net.Config.Log4NetConfigurationSe
ctionHandler,Log4net"/> </configSections> <log4net> <root>
<level value="DEBUG" /> <appender-ref ref="ADONetAppender" />
</root>
<appendername="ADONetAppender" type="log4net.Appender.ADONetAppend
er"> <bufferSize value="100" />
<connectionType value="System.Data.SqlClient.SqlConnection,
System.Data, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" />
<connectionString value="server=servername; uid=Lion; pwd=Lionman;
database=databasename" /> <commandText value="INSERT INTO Log
([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES
(@log_date, @thread, @log_level, @logger, @message,
@exception)" />

02 <parameter>

03 <parameterName value="@log_date"/> <dbType value="DateTime"/>
<layouttype="log4net.Layout.RawTimeStampLayout"/> </parameter>

04 <parameter>

<parameterName value="@thread"/> <dbType value="String"/>
05 <size value="255"/> <layouttype="log4net.Layout.PatternLayout">
<conversionPattern value="%thread"/> </layout> </parameter>

06 <parameter>

<parameterName value="@log_level"/> <dbType value="String"/>
07 <size value="50"/> <layouttype="log4net.Layout.PatternLayout">
<conversionPattern value="%level"/> </layout> </parameter>

08 <parameter>

<parameterName value="@logger"/> <dbType value="String"/>
09 <size value="255"/> <layouttype="log4net.Layout.PatternLayout">
<conversionPattern value="%logger"/> </layout> </parameter>

10 <parameter>
<parameterName value="@message"/> <dbType value="String"/>
11 <size value="4000"/> <layouttype="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/> </layout> </parameter>

12 <parameter>

<parameterName value="@exception"/> <dbType value="String"/>
13 <size value="2000"/>
<layouttype="log4net.Layout.ExceptionLayout"/> </parameter>
</appender> </log4net>

      In the connection string tag you need to change server name and database. You also can decide how to
define the security part of the connection string.
There are two way to define the security part

Use integrated Security

State the username and the password in the connection string.

In both cases you need to make sure that the user has access to the, SQL server, the database and the
databasetable that Log4Net is going to use.
If you use integrated security then the connection string should be like as
<connectionString value=”Data Source=servername;initial Catalog=databasename;Integrated
Security=True;”/> 
 5.    To use log4net put this as a local class variable:    private static readonly log4net.ILog log
=log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

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
.Colle
ctions
.Gener
ic;
using System.Text; 
using log4net;

using log4net.Confi
g; using log4net.Co
re;

using log4net.Reposi
tory.Hierarchy;

using log4net.Append
er;

  
  
{

   
   
  
pr
iv
at

st
at
ic 
re
ad
on
ly 
lo
g4
ne
t.
IL
og
lo
g
=l
og
4n
et
.L
og
Ma
na
ge
r.
Ge
tL
og
ge
r(
Sy
st
em
.R
ef
le
ct
io
n.
Me
th
od
Ba
se
.G
et
Cu
rr
en
tM
et
ho
d(
).
De
cl
ar
in
gT
yp
e)
;

1         static void Mai
3 n(string[] args)
1
        {
4

            log4net.Config.XmlConf
igurator.Configure();

            log.Debug("log
Debug");

1             log.I
7 nfo("log Info");

1             log.W
8 arn("log Warn");

1             log.Er
9 ror("log Error");

2             log.Fa
0 tal("log Fatal");

  
  
  
  
}

  
  
}

Now run the code then you can see the log stored in the database table.
 

 
 
 
 
 
 
 
 
 
 
 

 
 
3 Votes

Possibly related posts: (automatically generated)


 Troubleshooting Exchange 2007 Store Log/Database growth issues
 Exchange Database and Transactions log Reset

About Md Shaik Sadi


I am Md. Shaik Sadi. I have worked on different phases of software development life cycle. I have got
my B.Sc.(Engg) degree in COmputer Science and Engineering and started my carrer as a trainee
developer. Recently I am working on asp.net/2 and want to stablish my career on this platfrom.
View all posts by Md Shaik Sadi →

This entry was posted in Computer Science and tagged .Net, Asp.Net, Basic Programming, C#.Net, Computer


Science. Bookmark the permalink.

← .Net Remoting with a simple example


Building Blocks of .Net Platforms (CLR, CTS, CLS) →

Like
Be the first to like this post.
7 Responses to How to store log in database using log4net

1. Georg says:
September 16, 2008 at 6:42 am
Just want to mention that Log4Net has the possibility to reload configuration
dynamically when the config is changed, typical used if you change the log level when
the application is running.

To activate this you need to use the XmlConfigurator.ConfigureAndWatch instead of


XmlConfigurator.Configure()

The ConfigureAndWatch can be invoked using several methods my personal favorite is


using an assembly-level attribute:
[assembly: log4net.Config.XmlConfigurator(Watch=true)]

Best regards
Georg Jansen
http://www.l4ndash.com – Log analysis and monitoring made easy
Reply

2. Md. Shaik Sadi says:


September 16, 2008 at 9:01 am

thank for the comments …


it enriched my blog …

/author
Reply

3. satya says:
April 30, 2009 at 3:12 pm

Hi friend,

I used Log4net as above said.It is very good.


But i faced one problem is data which we entered in to database is not commited
immediatly.after closing app/dadaserver it is coming.
plase help on this waiting for your reply.
Thanks regards
satya
Reply

o samson says:
December 10, 2009 at 8:11 am

Set the buffersize value =1 to reflect the value in DB for each record
Reply

4. Roger says:
October 8, 2009 at 11:36 am

Hello,

I’m facing with the same problem.. data which we entered in to database is not
commited immediatly.after closing app/dadaserver it is coming.
Why happens this? How can data be commited without shutting down the server? I’m
using C#, not VB.

Thanks
Reply

5. Mac says:
April 11, 2010 at 6:39 pm

Great article. How do i get the identity of the log i have just inserted.

For eg. i want to display the id to user so that they can contact support team in case of
exception.

So once i call Log.Fatal it should return me the id. Can i override Fatal method?
Reply

6. Rafael says:
April 26, 2010 at 7:20 pm
Hi, I`m trying to store my logs in my database(SQL Server 2005), I tried to use this code
but nothing happened, Do I need to do anything else??
Maybe write another code in another class…
thanks..
Reply
Hi, I am totally new to Log4net. I have managed to get
something going by adding a config file and simple
logging I have hardcoded the value to be "c:\temp\log.txt"
but this is not good enough

The logs must go to the special folders

path=Enviroment.GetFolderPath(Enviroment.S
pecialFolder.CommonApplicationData;

and this path changes depending whether you are in


windows Server 2008 or winxp or vista etc...

How can I just change the location of the file in log4net


programmatically?

This is what I have done

<configSections>
<section name=“log4net“              
type=“log4net.Config.Log4NetConfigurationS
ectionHandler,Log4net“/>
  </configSections>
  <log4net>        
       <root>
             <level value=“DEBUG“ />
              <appender-ref
ref=“LogFileAppender“ />
        </root>
        <appender name=“LogFileAppender“
type=“log4net.Appender.RollingFileAppender
“ >
              <param name=“File“
value=“C:\temp\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>

--

class Program
{
  protected static readonly ILog log =
LogManager.GetLogger(typeof(Program));
   static void Main(string[] args)
   {
     
log4net.Config.XmlConfigurator.Configure()
;
       log.Warn(“Log something”);

     
path=Enviroment.GetFolderPath(Enviroment.S
pecialFolder.CommonApplicationData;

      //HOW CAN I CHANGE WHERE i LOG STUFF


   }
 }

Just need to figure out how I can change to log stuff to


where i want to

Any suggestions? Thanks a lot

c# log4net

link|flag edited

Colin Pickard
10.5k
@brix - you've managed to create a second account this one - stackoverf
question) and this one - stackoverflow.com/users/174863/brix (used to p
team@stackoverflow.com about getting them merged.

6 Answers
activenewestvotes

up log4net can handle this for you. Any appender property of type string can be formatted, in this

vote12 case, using the log4net.Util.PatternString option handler. PatternString even supports the


do SpecialFolder enum which enables the following elegant config:
wn vote <appender name="LogFileAppender"
accepted

type="log4net.Appender.RollingFileAppender" >
    <file type="log4net.Util.PatternString"
        value="%envFolderPath{CommonApplicationData}\\test.txt" />
    ...
</appender>

Here's a unit test that proofs the pudding:

[Test]
public void Load()
{
    XmlConfigurator.Configure();
    var fileAppender = LogManager.GetRepository()
        .GetAppenders().First(appender => appender is
RollingFileAppender);

    var expectedFile =
        Path.Combine(
            Environment.GetFolderPath(
                Environment.SpecialFolder.CommonApplicationData),
                "test.txt");

    Assert.That(fileAppender,
        Is.Not.Null & Has.Property("File").EqualTo(expectedFile));
}

The following test verifies that log4net actually writes to disk (which basically makes this an
"integration" test, not a unit test, but we'll leave it at that for now):

[Test]
public void Log4net_WritesToDisk()
{
    var expectedFile =
        Path.Combine(
            Environment.GetFolderPath(
                Environment.SpecialFolder.CommonApplicationData),
                "test.txt");

    if (File.Exists(expectedFile))
        File.Delete(expectedFile);

    XmlConfigurator.Configure();

    var log = LogManager.GetLogger(typeof (ConfigTest));


    log.Info("Message from test");

    LogManager.Shutdown();

    Assert.That(File.ReadAllText(expectedFile),
        Text.Contains("Message from test"));
}

NB: I strongly suggest using the compact property syntax demonstrated in the above sample.
Removing all those "<property name=" makes your config that much more readable.

link|flag edited Oct 11 '09 at 19:38 answered Oct 8 '09 at 6:45

Peter Lillevold
9,9211539
Hi THanks I have tried this but still does not log in application Data I have had a look on the web I have found
something called PatternString but I have no idea how to use it. Has anybody got an example? – brix Oct 9 '09 at 5:36
@brix - My initial answer didn't work, so I had to prove to myself that log4net can do this. PatternString is the
solution :) – Peter Lillevold Oct 9 '09 at 11:13
hi,tried your solution but for some reasons it does not log at all. I have copied what you suggested.Run the app but no
file created. Does yours actually create a file? thanks a lot – brix Oct 11 '09 at 5:20
@brix - it does create the file. One thing to have in mind is that log4net will not always flush data to disk immediately.
You should also check that the user running your app have enough permissions in that folder to create and write to
files. – Peter Lillevold Oct 11 '09 at 19:31
%envFolderPath{} does not appear to be part of the current (1.2.10) release of log4net. I had to pull r606477 from their
subversion repository to enable this very useful feature. I would expect this to be included in the next (1.2.11)
release. – rschuler Nov 18 '09 at 0:40
show 1 more comment

up You need to dig through your logger's IAppenders and set the FileAppender.File to your required

0
vote do
output path.

wn vote Here's a really good example.


link|flag answered Oct 8 '09 at 5:31
Cam Soper
38315
up As an alternative to doing this programatically, you can use environment variables and customizable

0 patterns in the configuration file. See this response to a similar question.


vote do Look at "PatternString for pattern based configuration" in the Log4Net V1.2.10 release notes.
wn vote Also if you are thinking of writing to a directory such as
Enviroment.SpecialFolder.CommonApplicationData you need to consider:

 Will all instances of your application for all users have write access to the log file? E.g. I
don't believe non-administrators will be able to write to
Enviroment.SpecialFolder.CommonApplicationData.

 Contention if multiple instances of your application (for the same or different users) are
attempting to the same file. You can use the "minimal locking model"
(seehttp://logging.apache.org/log4net/release/config-examples.html to allow multiple processes
to write to the same log file, but there probably will be a performance impact. Or you could
give each process a different log file, e.g. by including the process id in the filename using a
customizable pattern.
link|flag edited Oct 8 '09 at 7:01 answered Oct 8 '09 at 6:48

Joe
17.4k11648
up Guys, Thanks for your replies very helpful.

0
vote do Peter I am going to try whether that works as it's simple and could do the job.
wn vote
Joe, Thanks for your answer,this is def something i want to dig deeper but time is not on my side if
what Peter suggested works than I will be fine for now.

Need to deliver today.

thanks alot

link|flag answered Oct 8 '09 at 8:21


brix

Sorry for a late solution. Hopefully not too late! – Peter Lillevold Oct 9 '09 at 11:14
@brix - you've managed to create a second account this one - stackoverflow.com/users/174863/brix (used to post this
answer) and this one - stackoverflow.com/users/186134/brix (used to post the question). E-mail
team@stackoverflow.com about getting them merged. – ChrisF Oct 11 '09 at 20:01
up Hi Peter this is my Log4net file do you see something wrong for some reasons it still does not seem

0
vote do
to write to a file

wn vote <?xml version="1.0" encoding="utf-8" ?>


  <configuration>
    <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" >
  <file type="log4net.Util.PatternString"  
value="%envFolderPath{CommonApplicationData}\\test.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>
 </configuration>

public class Bar { private static readonly ILog Log = LogManager.GetLogger(typeof(Bar));

        public void DoIt()


        {
            const string filePath = @"c:\MyConfigFiles\Log4net.config";
            XmlConfigurator.Configure(new FileInfo(filePath));

            Log.Info("Test");
        }
}

link|flag answered Oct 12 '09 at 4:45

brix
1
up Looks like Peter's answer doesn't work for Log4net v1.2.10.0. An alternative method is

0 described here.
vote dow Basically the method is to implement a custom pattern converter for the log4net config file.
n vote
First add this class to your project:

public class SpecialFolderPatternConverter :


log4net.Util.PatternConverter
{
    override protected void Convert(System.IO.TextWriter writer, object
state)
    {
        Environment.SpecialFolder specialFolder =
(Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder),
base.Option, true);
        writer.Write(Environment.GetFolderPath(specialFolder));
    }
}

Then set up the File parameter of your FileAppender as follows:

<file type="log4net.Util.PatternString">
    <converter>
      <name value="folder" />
      <type value="MyAppName.SpecialFolderPatternConverter,MyAppName" />
    </converter>
    <conversionPattern
value="%folder{CommonApplicationData}\\SomeOtherFolder\\log.txt" />
  </file>

Basically the %folder tells it to look at the converter called folder which points it to the


SpecialFolderPatternConverter class. It then calls Convert on that class, passing in the
CommonApplicationData (or whatever) enum value.

Das könnte Ihnen auch gefallen