Creating a new log file each day - c#

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.
How can I create a new log file each day? The log file will be have the name in a format like MMDDYYYY.txt
How can I create it just after midnight in case it is running into all hours of the night?

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>

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.

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 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}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
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 & Warnings">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
</configuration>

Try out NLog (nlog-project.org). It is very flexible and easier to work with than Log4Net in my opinion.
Example NLog.config:
<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}"
fileName="${basedir}/${shortdate}/${windows-identity:domain=false}.${level}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</nlog>
For more examples (including other logging targets besides File) see NLog configuration examples on Github

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.

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.

Below is the appender XML that I am currently using.
Based on your requirements of
1) creating a log file for once a day and,
2) to have the extension of txt,
you should use an XML similar to what is below.
The XML below will create a log file called system-20121106.txt.
The only issue is that since file value is logs/system- your file while it is writing for current day will be system-. To get around this, you'd have to set your file value to logs/system.txt, but then you'd get system.txt.20121106.txt as the final file.
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs/system-" />
<appendToFile value="true"/>
<countDirection value="-1"/>
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd'.txt'" />
<maxSizeRollBackups value="0" />
<maximumFileSize value="10000KB" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>

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

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.

If you only need a simple TraceListener, I have a mini implementation here: https://github.com/datvm/DailyTraceListener
The output is also in CSV format so you can read it with Excel or any CSV reader.
Source code for the TraceListener:
public class DailyTraceListener : TraceListener
{
public bool UseUtcTime { get; private set; }
public string LogFolder { get; private set; }
public bool Disposed { get; private set; }
public bool HasHeader { get; private set; }
public string CurrentLogFilePath { get; private set; }
protected DateTime? CurrentLogDate { get; set; }
protected FileStream LogFileStream { get; set; }
protected StreamWriter LogFileWriter { get; set; }
private SemaphoreSlim LogLocker { get; set; } = new SemaphoreSlim(1, 1);
public DailyTraceListener(string logFolder)
{
this.LogFolder = logFolder;
}
public DailyTraceListener UseUtc()
{
this.UseUtcTime = true;
return this;
}
public DailyTraceListener UseHeader()
{
this.HasHeader = true;
return this;
}
protected virtual void WriteHeader()
{
this.LogFileWriter.WriteLine(string.Format("{0},{1},{2},{3},{4}",
"Time",
"Type",
"Source",
"ID",
"Message"));
}
protected virtual string FormatTime(DateTime time)
{
return time.ToString("o");
}
private DateTime GetCurrentTime()
{
if (this.UseUtcTime)
{
return DateTime.UtcNow;
}
else
{
return DateTime.Now;
}
}
private void InitializeLogFile()
{
this.CheckDisposed();
try
{
if (this.LogFileWriter != null)
{
this.LogFileWriter.Dispose();
}
if (this.LogFileStream != null)
{
this.LogFileWriter.Dispose();
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
var currentTime = this.GetCurrentTime();
var fileName = $"{currentTime.ToString("yyyy-MM-dd")}.log";
this.CurrentLogFilePath = Path.Combine(this.LogFolder, fileName);
// Ensure the folder is there
Directory.CreateDirectory(this.LogFolder);
// Create/Open log file
this.LogFileStream = new FileStream(this.CurrentLogFilePath, FileMode.Append);
this.LogFileWriter = new StreamWriter(this.LogFileStream);
// Write Header if needed
if (this.LogFileStream.Length == 0 && this.HasHeader)
{
this.WriteHeader();
}
}
private void CheckFile()
{
this.CheckDisposed();
var currentTime = this.GetCurrentTime();
if (this.CurrentLogDate == null || currentTime.Date != this.CurrentLogDate)
{
this.InitializeLogFile();
this.CurrentLogDate = currentTime.Date;
}
}
private void CheckDisposed()
{
if (this.Disposed)
{
throw new InvalidOperationException("The Trace Listener is Disposed.");
}
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
var time = this.FormatTime(this.GetCurrentTime());
this.WriteLine(string.Format("{0},{1},{2},{3},{4}",
time,
eventType,
EscapeCsv(source),
id.ToString(),
EscapeCsv(message)));
}
public override void Write(string message)
{
try
{
this.LogLocker.Wait();
this.CheckDisposed();
this.CheckFile();
var currentTime = this.GetCurrentTime();
this.LogFileWriter.Write(message);
this.LogFileWriter.Flush();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
finally
{
this.LogLocker.Release();
}
}
public override void WriteLine(string message)
{
this.Write(message + Environment.NewLine);
}
protected string EscapeCsv(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ',' || input[i] == '\n')
{
input = input.Replace("\"", "\"\"");
return $"\"{input}\"";
}
}
return input;
}
protected override void Dispose(bool disposing)
{
this.Disposed = true;
try
{
this.LogFileWriter?.Dispose();
this.LogFileStream?.Dispose();
this.LogLocker.Dispose();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
base.Dispose(disposing);
}
}

Related

Formatter not set in custom trace listener for EnterpriseLibrary logging

I have created a custom trace listener for the EnterpriseLibrary logging block, but the Formatter property is always null.
This is the code:
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using System;
using System.Diagnostics;
namespace test {
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class TestTraceListener : CustomTraceListener {
public override void Write(string message) {
Console.Write(message);
}
public override void WriteLine(string message) {
Console.WriteLine(message);
}
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) {
LogEntry entry = data as LogEntry;
if (entry != null) {
if (Formatter != null) {
string formatted = Formatter.Format(entry);
WriteLine(formatted);
} else {
WriteLine(entry.Message);
}
} else {
base.TraceData(eventCache, source, eventType, id, data);
}
}
}
class Program {
static void Main(string[] args) {
Logger.SetLogWriter(new LogWriterFactory().Create());
LogEntry entry = new LogEntry("This is a test", "General", 0, 0, TraceEventType.Information, null, null);
Logger.Write(entry);
}
}
}
And this is the configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="loggingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="true" />
</configSections>
<loggingConfiguration name="logging" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Console Trace Listener"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.SystemDiagnosticsTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
formatter="Simple Formatter"
type="test.TestTraceListener, test"
traceOutputOptions="DateTime, Timestamp, ThreadId" />
</listeners>
<formatters>
<add name="Simple Formatter"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="{timestamp(local:dd/MM/yy HH:mm:ss.fff)} [{severity}]: {message}" />
</formatters>
<categorySources>
<add switchValue="Information" name="General">
<listeners>
<add name="Console Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="Warning" name="Logging Errors & Warnings" />
</specialSources>
</loggingConfiguration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>
If I understood correctly, my listener should have the "Simple Formatter" formatter that I declared in the configuration file in its Formatter property, but this is not the case.
What am I missing?
I solved the problem with the Enterprise Library Configuration Tool (I could make it work for VS 2015 following the instructions here: Does Enterprise Library 6 work with Visual Studio 2013 and/or 2015?).
The problem was a wrong value of the listenerDataType attribute, the XML declaration of the listener should have been the following:
<add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
type="test.TestTraceListener, test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
name="Console Trace Listener"
formatter="Simple Formatter" />

How to Maintaing Error log of a month in C#?

I am maintaing error log in c# application but on daily basis. Now I want to maintain it one a monthly basis. how to check in folder for already created file a month ago n also if not created then create it.
public static void WriteError(string errorMessage)
{
try
{
string path = "~/Error/" + DateTime.Today.ToString("dd-MM-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("{0}", DateTime.Now.ToString());
//w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
". Error Message:" + errorMessage;
w.WriteLine(err);
w.WriteLine("__________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
if (GlobalVar.DebugLevel == Convert.ToInt16(EnDebugLevel.Medium))
ErrorLog.WriteError(ex.Message);
//WriteError(ex.Message);
}
}
}
pls help me to resolve this issue.
thank you.
Don't deal with logging yourself, there are libraries that can help you with that. Check out log4net
You could use a rolling file appender to automatically create logs for you every month.
You can configure it like so:
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender,log4net">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<param name="StaticLogFileName" value="true"/>
<file type="log4net.Util.PatternString" value="C:\log4net\TestLog_%date{yyyyMM}.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMM" />
<maximumFileSize value="1000KB" />
<maxSizeRollBackups value="3" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %date{dd MMM yyyy HH:mm:ss,fff} %logger - %message%newline" />
</layout>
</appender>
Then logging would be just a matter of doing:
public class LogTest
{
private static readonly ILog logger = LogManager.GetLogger(typeof(LogTest));
static void Main(string[] args)
{
logger.Error("an error!");
}
}
To learn more about configuring it, check out this tutorial

Log messages going to previously created log file

I am using enterprise library 5.0 logging in my asp.net site,
My web.config file is as follows:
<?xml version="1.0"?>
<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="FlatFileLogging" tracingEnabled="true"
defaultCategory="General">
<listeners>
<add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="C:\Logs\2013-06-28 14-21-53.log" header="" footer=""
formatter="Text Formatter" traceOutputOptions="DateTime" />
</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}, {severity}, {message}" name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Flat File Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Flat File Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0">
</compilation>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
</configuration>
I am changing log file path using following function:
public static void SetLogFilePath(string filePath)
{
//string logdirectory = AppDomain.CurrentDomain.BaseDirectory + "Logs\\";
//if (!Directory.Exists(logdirectory))
// Directory.CreateDirectory(logdirectory);
//logFilePath = logdirectory + (string.IsNullOrWhiteSpace(txtBatchName.Text) ? "" : (txtBatchName.Text + " ")) + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".log";
if (!File.Exists(filePath))
File.Create(filePath);
ConfigurationFileMap objConfigPath = new ConfigurationFileMap();
// App config file path.
string appPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
objConfigPath.MachineConfigFilename = appPath;
Configuration entLibConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
LoggingSettings loggingSettings = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
TraceListenerData traceListenerData = loggingSettings.TraceListeners.Get("Flat File Trace Listener");
FlatFileTraceListenerData objFlatFileTraceListenerData = traceListenerData as FlatFileTraceListenerData;
objFlatFileTraceListenerData.FileName = filePath;
entLibConfig.Save();
}
Whenever I change log file path and send log messages to file, the logs do not go to newly created file. Log messages go to previously set file path. seems that new setting is not reflecting immediately.
string path = "C:\\Logs\\" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".log";
SetLogFilePath(path);
Logger.Write(message, "General", 1, 0, System.Diagnostics.TraceEventType.Information);
How to refresh the new settings to code immediately?
How do you define "immediately"? If you mean in the middle of the executing request then I don't think you can do that via configuration since the configuration will not be refreshed for that request.
Here's an implementation that seems to work for me based on the blog post Enterprise Library Programmatic Configuration. I don't write the config change back to disk but change it in memory instead.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>()
.Write("test", "General");
string path = "C:\\Logs\\anotherlogfile.log";
SetLogFilePath(path);
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>()
.Write("Another test", "General");
}
public void SetLogFilePath(string filePath)
{
ConfigurationFileMap objConfigPath = new ConfigurationFileMap();
// App config file path.
string appPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
objConfigPath.MachineConfigFilename = appPath;
Configuration entLibConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
LoggingSettings loggingSettings = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
TraceListenerData traceListenerData = loggingSettings.TraceListeners.Get("Flat File Trace Listener");
FlatFileTraceListenerData objFlatFileTraceListenerData = traceListenerData as FlatFileTraceListenerData;
objFlatFileTraceListenerData.FileName = filePath;
IUnityContainer container = new UnityContainer();
container.AddNewExtension<EnterpriseLibraryCoreExtension>();
// Configurator will read Enterprise Library configuration
// and set up the container
UnityContainerConfigurator configurator = new UnityContainerConfigurator(container);
var loggingXmlConfigSource = new SerializableConfigurationSource();
loggingXmlConfigSource.Add(LoggingSettings.SectionName, loggingSettings);
// Configure the container with our own custom logging
EnterpriseLibraryContainer.ConfigureContainer(configurator, loggingXmlConfigSource);
// Wrap in ServiceLocator
IServiceLocator locator = new UnityServiceLocator(container);
// Release lock(s) on existing file(s)
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>().Dispose();
// And set Enterprise Library to use it
EnterpriseLibraryContainer.Current = locator;
}
}
public class SerializableConfigurationSource : IConfigurationSource
{
Dictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>();
public SerializableConfigurationSource()
{
}
public ConfigurationSection GetSection(string sectionName)
{
ConfigurationSection configSection;
if (sections.TryGetValue(sectionName, out configSection))
{
SerializableConfigurationSection section = configSection as SerializableConfigurationSection;
if (section != null)
{
using (StringWriter xml = new StringWriter())
using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(xml))
{
section.WriteXml(xmlwriter);
xmlwriter.Flush();
MethodInfo methodInfo = section.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(section, new object[] { XDocument.Parse(xml.ToString()).CreateReader() });
return configSection;
}
}
}
return null;
}
public void Add(string sectionName, ConfigurationSection configurationSection)
{
sections[sectionName] = configurationSection;
}
public void AddSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public void Remove(string sectionName)
{
sections.Remove(sectionName);
}
public void RemoveSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public event EventHandler<ConfigurationSourceChangedEventArgs> SourceChanged;
public void Dispose()
{
}
}

Why is log4net not writing to a file?

I have added all parts of log4net, however it doesn't write to the file.
I'm working with the VS2012 LoadTest project.
Neither the System.Console.WriteLine or Debug.WriteLine() work, when running the LoadTest project.
I've added the assembly info line:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "web.config", Watch = true)] //For log4net 1.2.10.0
I've:
- added webconfig section
- initialized an configured an XML initializer
- initialized new log4net with the proper log
My app.config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Settings_CacheExplosion.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
My class:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebAndLoadTestProject1
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using log4net;
using log4net.Core;
using Microsoft.VisualStudio.TestTools.WebTesting;
public class Settings_CacheExplosion : WebTest
{
private static readonly ILog activityLog = LogManager.GetLogger("Activity");
private static int _ctidsCounter { get; set; }
public static int CtidsCounter
{
get
{
if (_ctidsCounter == 2000)
{
_ctidsCounter = 1000;
}
return _ctidsCounter++;
}
set
{
_ctidsCounter = value;
}
}
public Settings_CacheExplosion()
{
this.PreAuthenticate = true;
CtidsCounter = 1000;
log4net.Config.XmlConfigurator.Configure();
}
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
WebTestRequest request1 = new WebTestRequest("http://clientservice.mam.qasite-services.com/settings");
request1.Method = "POST";
Debug.WriteLine(string.Format("ctid={0}", CtidsCounter));
request1.QueryStringParameters.Add("ctid", CtidsCounter.ToString(), false, false);
StringHttpBody request1Body = new StringHttpBody();
request1Body.ContentType = "";
request1Body.InsertByteOrderMark = false;
request1Body.BodyString = "";
request1.Body = request1Body;
activityLog.Debug(string.Format("ctid={0}", CtidsCounter));
//Console.WriteLine(string.Format("ctid={0}", CtidsCounter));
yield return request1;
request1 = null;
}
}
}
If you want log4net to read from the app.config, you have to add this to your AssemblyInfo.cs file:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Looking at your app.config:
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
This works to ensure that the app will refuse to start on .NET 4.0 with an error on startup.
If you are using Framework .NET4.5, log4net does not support it. See frameworks section in http://logging.apache.org/log4net/release/features.html
use <param name = "Activity" value="Settings_CacheExplosion.txt" /> instead of <file value="Settings_CacheExplosion.txt" />. in your xml configuration section.

Set log name in appender of log4net

I have class MyLogger, where I use log4net. How can I modify my appender to save log in specific logname (I want to set it by parameter logName).
public void AddEntry(string source, string logName, string contextInfo, string message, EventLogEntryType eventType)
{
log4net.ILog Log = log4net.LogManager.GetLogger(source);
Log.Error(String.Format("Context Info: {0}{1}{2}{3}", contextInfo, Environment.NewLine, Environment.NewLine, message));
}
<log4net>
<root>
<priority value="ALL" />
<appender-ref ref="EventLogAppender" />
</root>
This is myAppender. Now it writes in common logtype Application.
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger (%property{myContext}) [%level]- %message%newline" />
</layout>
</appender>
</log4net>
I think what you are looking for is this:
<param name="LogName" value="MyLog" />
Some more information can be found here. If you do something like this you may want to have a look at this issue as well. Basically this is about registering your application so that the eventlog knows about it.
Edit (configuration by code):
Did not test it but that ought to do the trick:
foreach (AppenderSkeleton appender in this.Logger.Repository.GetAppenders())
{
var eventlogAppender = appender as EventLogAppender;
if (eventlogAppender != null)
{
eventlogAppender.LogName = "MyLog";
eventlogAppender.ActivateOptions();
break;
}
}
You could add some tests to verify that there is only one EventLogAppender, but probably you do not need to bother to do so.
this works:
<param name="LogName" type="log4net.Util.PatternString" value="%property{LogName}" />

Categories

Resources