93

When I set the file value to logs\log-file.txt, where exactly will it create this folder? In the /bin directory?

My web.config looks like this:

<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="logs\log-file.txt" />
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
</log4net>

Is this the correct way to log:

ILog logger = LogManager.GetLogger(typeof(CCController));
logger.Error("Some Page", ex);  // where ex is the exception instance
Jeroen
  • 60,696
  • 40
  • 206
  • 339
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

10 Answers10

78

If you want your log file to be place at a specified location which will be decided at run time may be your project output directory then you can configure your .config file entry in that way

<file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" />

and then in the code before calling log4net configure, set the new path like below

 log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
 log4net.Config.XmlConfigurator.Configure();

How simple is it? :)

NealWalters
  • 17,197
  • 42
  • 141
  • 251
Avijit Chatterjee
  • 1,015
  • 9
  • 9
  • 2
    Great trick, it helps putting all the configuration in one place :) – Hoàng Long Oct 09 '15 at 06:42
  • 1
    What if you want multiple log files in one program, each of them in a different path determined at run time? Is there a way to set the property LogFileName not in some global shared context? – Jimmy Mar 16 '18 at 18:19
  • There are other patterns, such as %date{}, that can be used once you apply the log4net.Util.PatternString type: https://logging.apache.org/log4net/log4net-1.2.11/release/sdk/log4net.Util.PatternString.html – Justin Jun 04 '20 at 23:49
64

it will create the file in the root directory of your project/solution.

You can specify a location of choice in the web.config of your app as follows:

   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:/ServiceLogs/Olympus.Core.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value=".yyyyMMdd.log" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
      <maxSizeRollBackups value="-1" />
      <countDirection value="1" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
      </layout>
    </appender>

the file tag specifies the location.

Keith
  • 20,636
  • 11
  • 84
  • 125
Oladipo Olasemo
  • 2,010
  • 24
  • 31
20

The file value can either be an absolute path like "c:\logs\log.txt" or a relative path which I believe is relative to the bin directory.

As far as implementing it, I usually place the following at the top of any class I plan to log in:

private static readonly ILog Log = LogManager.GetLogger( 
MethodBase.GetCurrentMethod().DeclaringType);

Finally, you can use it like so:

Log.Debug("This is a DEBUG level message.");
Ben.Vineyard
  • 1,149
  • 8
  • 14
  • 7
    hmm..it doesn't seem to be creating the log file anywhere, and I am not getting any error? – Blankman May 12 '10 at 03:37
  • 2
    Sounds like a permissions issues. I would map the configuration to an absolute path outside of your web directory. Following that, make sure that the log file and folder have permissions to allow the asp.net worker process proper access. – Ben.Vineyard May 12 '10 at 03:52
  • For a relative path I like the log file to be at project level: – Dave Mateer Jan 26 '15 at 15:24
  • @Blankman I had a similar problem. The issue is not the path or the permission but that I forgot to call the configure to start up the logging. Please see the answer to the other stack overflow question. http://stackoverflow.com/questions/20512548/how-to-check-log4net-log-path – Nap Apr 24 '15 at 02:25
12

Log4net is saving into your project folder. Something like: \SolutionFolder\ProjectFolder\bin\SolutionConfiguration\logs\log-file.txt.

Where:

  • SolutionFolder is where you save your solution
  • ProjectFolder is the folder where your project lives into the solution and
  • SolutionConfiguration is the folder that contais all the binaries of your project (the default is Debug or Release)

Hope this helps!

Perception
  • 79,279
  • 19
  • 185
  • 195
  • I realise this is 9 years later but this answer was the clearest to me. When you don't specify a `` for the appender it does indeed still default to `\solutionName\projectName\bin\Debug` my question is, is this ok? ie. is it good practise to have the log file in same directory as binary files? – amy Jul 22 '21 at 11:29
6
FileAppender appender = repository.GetAppenders().OfType<FileAppender>().FirstOrDefault();
if (appender != null)
    logger.DebugFormat("log file located at : {0}", appender.File);
else
    logger.Error("Could not locate fileAppender");
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Mickey Perlstein
  • 2,508
  • 2
  • 30
  • 37
  • 2
    ILoggerRepository repository = log4net.LogManager.GetAllRepositories().FirstOrDefault(); – Louis Somers Mar 29 '18 at 07:56
  • 2
    The repository is already here: `yourlogger.Logger.Repository`. So you can make this: `yourlogger.Info($"Logfile opened: {m_Logger.Logger.Repository.GetAppenders().OfType().FirstOrDefault()?.File}");`. Note that it won't break if something is `null`. – Nicolas Oct 02 '18 at 14:29
4

For the log folder and file stuff, go with @Bens answer.

I will comment on the creating log part, though. Imo there is no correct way. When coding loggers manually I do it the way you're doing it:

ILog logger = LogManager.GetLogger(typeof(CCController));

because it is short and concise.

That said, I do not create the logger instances inside the classes these days, I let my IoC container inject it for me.

Community
  • 1
  • 1
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
1

I was developing for .NET core 2.1 using log4net 2.0.8 and found NealWalters code moans about 0 arguments for XmlConfigurator.Configure(). I found a solution by Matt Watson here

        log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
        var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
andrew pate
  • 3,833
  • 36
  • 28
0

I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.

I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.

griegs
  • 22,624
  • 33
  • 128
  • 205
0

if you want to choose dynamically the path to the log file use the method written in this link: method to dynamic choose the log file path.

if you want you can set the path to where your app EXE file exists like this -

var logFileLocation = System.IO.Path.GetDirectoryName
(System.Reflection.Assembly.GetEntryAssembly().Location);

and then send this 'logFileLocation' to the method written in the link above like this:

Initialize(logFileLocation);

and you are ready to go! :)

Ben.S
  • 708
  • 1
  • 5
  • 24
0

In your case, the log file will be in bin\Debug\netcoreapp3.1\ folder and this may depends on your framework too.

I used Asp.Net core 3.1 so the folder path is bin\Debug\netcoreapp3.1\

Raj K
  • 568
  • 6
  • 11