Error with Custom Trace Listener - c#

In my Application (C# Winforms) Im trying to implement a custom trace listener like This one here.
But Im getting a configuration error.
Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="TextListener"
type="MyApp.TextLogTraceListener, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
initializeData="c:\\trace.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
Custom Listener
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace MyApp
{
public class TextLogTraceListener : System.Diagnostics.TextWriterTraceListener
{
public TextLogTraceListener()
{
}
public TextLogTraceListener(string name)
: base(name)
{
}
public override void Write(string message)
{
using (FileStream fs = new FileStream("C:\\trace.log", FileMode.Append))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(message);
}
}
public override void WriteLine(string message)
{
using (FileStream fs = new FileStream("C:\\trace.log", FileMode.Append))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(message);
}
}
}
}
Error Im Getting
An unhandled exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.dll
Additional information: Couldn't find type for class MyApp.TraceListeners.TextLogTraceListener, MyApp.TraceListeners, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
My Main objective is to catch all Debug/Trace information into my own custom text file.
UPDATE
I fixed the namespace which seemed to remove the error and as Martin suggested I changed the initizeData. Now I have removed the error thrown in VS I am still not getting data reported to the text file.
Im writing trace logs like this.
Trace.WriteLine("Application Starting");
Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="TextListener"
type="MyApp.TextLogTraceListener, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
initializeData="c:\trace.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
</configuration>

Related

System.InvalidOperationException : No connection string named 'db_modelContainer' could be found in the application config file

I wanted to test a method that creates an account.
public users CreateAccount(string _username, double _weight, string _password)
{
using (var db = new db_modelContainer())
{
Daily_summary summary = new Daily_summary { weight = _weight};
Users_dishes_gallery user_dishes = new Users_dishes_gallery { };
var x = db.usersSet;
foreach (var i in x)
{
if (_username == i.name)
{
throw new CreateAccountFailException("Username is already occupied!");
}
}
users newuser = new users { name = _username, weight = _weight, password = _password};
db.usersSet.Add(newuser);
db.SaveChanges();
return newuser;
}
}
I have another xUnit project where I wanted to write those tests. I prepared my first file:
[Fact]
//[AutoRollback]
public void CreateAccount_GivenNotOccupiedUsername_CreateSucceed()
{
string expectedLogin = "test";
string expectedPassword = "test";
double expectedWeight = 30;
Users user = new Users();
users createduser = user.CreateAccount(expectedLogin, expectedWeight,expectedPassword);
// Assert
Assert.Equal(expectedLogin, createduser.name);
Assert.Equal(expectedPassword, createduser.password);
Assert.Equal(expectedWeight, createduser.weight);
}
But I'm still getting that error.
error from vs
System.InvalidOperationException : No connection string named 'db_modelContainer' could be found in the application config file.
I tried many ways. Main project with edmx inside is my start project. I also added a link to App. config from my main project so my test project has access to the connection string but it didn't help me.
link to app.config
Below is my App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<connectionStrings>
<add name="db_modelContainer" connectionString="metadata=res://*/Database.db_model.csdl|res://*/Database.db_model.ssdl|res://*/Database.db_model.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SQLEXPRESS;initial catalog=Dietaverse_database;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Where is your App.Config file? If it's not hosted in the same project as your Unit Test then it probably isn't being loaded into the program. Try making a copy of your App.Config file and adding it to your Unit Test project and setting the property to "Copy Always"

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" />

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()
{
}
}

An error occurred creating the configuration section handler

I have a dot.NET 4.0 web application with a custom section defined:
<configuration>
<configSections>
<section name="registrations" type="System.Configuration.IgnoreSectionHandler, System.Configuration, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="true" restartOnExternalChanges="true" allowLocation="true"/>
....
at the end of the web.config file I have the respective section:
....
<registrations>
.....
</registrations>
</configuration>
Every time I call System.Configuration.ConfigurationManager.GetSection("registrations"); I get the following exception:
An error occurred creating the configuration section handler for registrations: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047) (C:\...\web.config line 13)
I'm also using Unity but don't know if that's in any way related to the error.
Have you faced this error before? How can I fix it? Do I need to replace the IgnoreSectionHandler with something else?
Given this app.config:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="registrations" type="MyApp.MyConfigurationSection, MyApp" />
</configSections>
<registrations myValue="Hello World" />
</configuration>
Then try using this:
namespace MyApp
{
class Program
{
static void Main(string[] args) {
var config = ConfigurationManager.GetSection(MyConfigurationSection.SectionName) as MyConfigurationSection ?? new MyConfigurationSection();
Console.WriteLine(config.MyValue);
Console.ReadLine();
}
}
public class MyConfigurationSection : ConfigurationSection
{
public const String SectionName = "registrations";
[ConfigurationProperty("myValue")]
public String MyValue {
get { return (String)this["myValue"]; }
set { this["myValue"] = value; }
}
}
}
You are missing the Namespace in the type attribute of your section in App.Config. Infact you dont need the full assembly info in there either. only the namespace is enough
Updated 1
yourcustomconfigclass config =(yourcustomconfigclass)System.Configuration.ConfigurationManager.GetSection(
"registrations");
and in config file only write
<section name="registrations" type="System.Configuration.IgnoreSectionHandler" requirePermission="true" restartOnExternalChanges="true" allowLocation="true"/>

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

Categories

Resources