views:

396

answers:

8

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?
+2  A: 

You don't need to create it at a particular time- in the simplest case you can just check if there is a logfile with today's date as it's name when you start the logging service for the app and if there isn't you can create one before you start appending to it.

The only case you need to be particularly aware of with this setup is when the application runs past midnight.

glenatron
+1  A: 

Hi, use log4net. This is one of the most commonly used library for logging.

It can be easily configured as you like, please refer to samples.

portland
Specifically: RollingFileAppender -- <rollingStyle value="Date" />, <datePattern value=".yyyyMMdd" />
Jeffrey Knight
+1  A: 

When you log something, check to see if a file with the current date exists, if not - create it. Simple as that :)

if(fileExists(todaysDate + ".txt")){
  appendToLogFile(message);
}else{
  createFile(todaysDate + ".txt");
  appendToLogFile(message);
}
Undeph
A: 

There is no need to create it until you need it, use:

 file = new StreamWriter(path, true, new UTF8Encoding(false));

(or maybe a different encoding.) This will create the file is it does not exist, or start to append to it.

Then it is a matter of creating the filename, and just using that.

Richard
+1  A: 

I'd recommend something like this:

    string logFile = DateTime.Now.ToString("yyyyMMdd") + ".txt";
    if (!System.IO.File.Exists(logFile))
    {
         System.IO.File.Create(logFile);

    }
//append to logFile here...

Is there a reason you want something to create it after midnight? Why not just create it if it doesn't exist when you go to log the error?

Also noticed that I changed the date format. This will allow you to sort files by name and get them in order. I always use this format when messing with dates in any way.

Abe Miessler
+11  A: 

From the Log4Net config examples: http://logging.apache.org/log4net/release/config-examples.html

This example show 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="logfile" />
    <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>
Daniel Dyson
+1 for mentioning Log4Net
Pretzel
+1  A: 

Try out NLog (nlog-project.org). It is very flexible and easier to work with than Log4Net in my opinion.

ifwdev
+1  A: 

Others have mentioned Log4Net, so I'll go ahead and pimp the Enterprise Library Logging Block, which is also quite capable of doing what you want.

Could you please include some code that shows how easy it would be to make this roll every day? Is it easier than the log4Net example? – Daniel Dyson

Sure. Typically, one would use Enterprise Library Configuration Tool to build the configuration; this tool takes a little getting used to, but once you understand how it works, it's pretty powerful. That said, you can also edit the app.config by hand.

Here is the output of the tool I mentioned, which dumps pretty much everything everything into a rolling flat file that rolls every day (or if it exceeds 2MB). The formatting is the default provided by the tool.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <loggingConfiguration name="" tracingEnabled="true" defaultCategory="Category">
        <listeners>
            <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                formatter="Text Formatter" rollInterval="Day" rollSizeKB="2000" />
        </listeners>
        <formatters>
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
                name="Text Formatter" />
        </formatters>
        <categorySources>
            <add switchValue="All" name="Category">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </add>
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </allEvents>
            <notProcessed switchValue="All" name="Unprocessed Category">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </notProcessed>
            <errors switchValue="All" name="Logging Errors &amp; Warnings">
                <listeners>
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
</configuration>
Randolpho
Could you please include some code that shows how easy it would be to make this roll every day? Is it easier than the log4Net example?
Daniel Dyson
@Daniel Dyson: done.
Randolpho
+1 Thanks. That is interesting
Daniel Dyson