Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new log file each day

As the title implies how can I create a new log file each day in C#? Now the program may not necessarily run all day and night but only get invoked during business hours. So I need to do two things.

  1. How can I create a new log file each day? The log file will be have the name in a format like MMDDYYYY.txt
  2. How can I create it just after midnight in case it is running into all hours of the night?
like image 727
Jason T. Avatar asked May 24 '10 15:05

Jason T.


People also ask

How do you create a new log file for each time the application runs in C#?

You have to use both the Cached Layout Renderer and the longdate variable. To understand why this works, you need to understand how they they work, and how they interact. Using the longdate variable in your log name will pretty much guarantee a new log file on every execution...


1 Answers

Update 2018: I prefer to use NLog now

Previous answer about log4net:

This example shows how to configure the RollingFileAppender to roll log files on a date period. This example will roll the log file every minute! To change the rolling period adjust the DatePattern value. For example, a date pattern of "yyyyMMdd" will roll every day.
See System.Globalization.DateTimeFormatInfo for a list of available patterns.

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="C:\temp\rolling.log" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd-HHmm" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
</appender>
like image 183
Daniel Dyson Avatar answered Oct 23 '22 19:10

Daniel Dyson