We use the EnterpriseLibray to log error in our application. For some reason the log file stay locked until the pplication service is stopped.
Is there any option to leave the file unlocked when it's not in use? My goal is to create an external process (a kind of watchdog) that copy and zip the log file....but it's locked.
Any idea ?
This is what my app.config look like :
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Culture=neutral, PublicKeyToken=31bf3856ad364e35" fileName="Server.log" rollSizeKB="2024" footer="----------------------------------------" formatter="NovaLogFormatter" header="- NEW TRACE ----------------------------------------" rollFileExistsBehavior="Increment" maxArchivedFiles="20" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Culture=neutral, PublicKeyToken=31bf3856ad364e35" template="Timestamp: {timestamp(local)}{newline}
Message: {message}{newline}
Category: {category}{newline}
Severity: {severity}{newline}
Title: {title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
Extended Properties:{newline}{dictionary({key}{newline}{value}{newline})}" name="NovaLogFormatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</add>
<add switchValue="All" name="Data" />
<add switchValue="All" name="Security" />
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings" />
</specialSources>
</loggingConfiguration>
The locking behavior is by design and inherited from the TraceListener base class.
There are a few options available to you:
Read through the lock
Since you are using RollingFlagFileTraceListener you could operate on archived files (which are no longer locked)
You could release the file lock after every write
Read Through the Lock
You can use code like this to read the contents of the file even though it's locked:
using(var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using(var sr = new StreamReader(fs))
{
while(!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
This should allow the watchdog to copy the file contents but you may have to manage state so that the same log entries are not copied multiple times (if that's important to you).
Copy Archived Files
Another idea is to only zip files that have been archived by the RollingFlatFileTraceListener. These files will not be locked. However, archiving does not occur at regular intervals so this may not be a good fit.
Release Lock
Another option is to release the lock by disposing of the LogWriter after writing a LogEntry. This will work but has a performance overhead (opening and closing the file) and requires you to manage concurrency (to avoid closing the LogWriter when another thread is using it).
Bonus
I hesitate to mention it but you could write a custom trace listener that does whatever you want. Probably not a great use of time but it is an option.
Related
I followed youtube videos and articles on net and implemented this. But it never writes to my log file. Tried with all suggestions around many forums with no use.
not sure where I went wrong. I had this inside class library.
app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net><appender name="myLogAppender" type="log4net.Appender.RollingFileAppender" >
<file value="D:\\Log4NetLog.txt" /><layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%n" /></layout></appender>
<logger name="myLog"><level value="ALL"></level><appender-ref ="myLogAppender" />
</logger></log4net></configuration>
and in the Assembly.info.cs:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "app.config", Watch = true)]
and in the class file:
ILog mylog = LogManager.GetLogger("myLog");
string xx = "tokensalt";
mylog.Info(xx);
If you configuration is in you app.config, you do not need to specify the file in the Configurator:
[assembly: log4net.Config.XmlConfigurator()]
Also the watch is not very usefull, when you change the app.config file. The applpication will restart anyway and the file will be reloaded.
If that is not working, I would guess that the path you logging to is not accessible by the web user you are logging with.
->>> <file value="D:\\Log4NetLog.txt"
Make sure you choose a path where you have access.
Use the file appender and not the rolling appender, the rolling appender was made for backup purposes, for example if your file exceeds 10mb then it will write to your rolling appender and you can decide how many files of 10mb you write there, from the log4net site:
RollingFileAppender can roll log files based on size or date or both
depending on the setting of the RollingStyle property. When set to
Size the log file will be rolled once its size exceeds the
MaximumFileSize. When set to Date the log file will be rolled once the
date boundary specified in the DatePattern property is crossed. When
set to Composite the log file will be rolled once the date boundary
specified in the DatePattern property is crossed, but within a date
boundary the file will also be rolled once its size exceeds the
MaximumFileSize. When set to Once the log file will be rolled when the
appender is configured. This effectively means that the log file can
be rolled once per program execution.
Here is a working web.config example that should work for you:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.appender.FileAppender">
<file value="C:\MyLogs\MyLogFile.txt"/>
<appendToFile value="true"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%logger] %level - %message%newline%exception"/>
</layout>
</appender>
<root>
<level value="DEBUG"></level>
<appender-ref ref="FileAppender"></appender-ref>
</root>
</log4net>
I have inherited an application which uses the configuration manager class to store and retrieve settings. In the app.config class there is custom section group "userSettings" which includes a "Server" property.
In the app.config file this value is defined as "a14". In Settings.Designer.vb the default is specified as "a5" yet when I try to access My.Settings.Server it brings back the value "a10", which is a value I previously used in the app.config file.
Not having much experience with the configuration manager, I am at a loss to determine where it is retrieving this value from and what I need to change so that it retrieves the correct server value.
For brevity, I have removed other settings from the code sample.
app.config:
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="WorkstationApp.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
...
<userSettings>
<WorkstationApp.My.MySettings>
<setting name="Server" serializeAs="String">
<value>a14</value>
</setting>
</WorkstationApp.My.MySettings>
</userSettings>
Settings.Designer.vb:
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("a5")> _
Public Property Server() As String
Get
Return CType(Me("Server"),String)
End Get
Set
Me("Server") = value
End Set
End Property
Application code: (server is being set to "a10", but I want it to have the app.config value of "a14").
Dim Server As String = My.Settings.Server
It looks like I was expecting the wrong thing (well duh). I had these settings set as User settings, which are stored in the /appdata/ folder and had nothing to do with the app.config file at all.
The user config file had been set with the initial values and had never been modified subsequently with a My.Settings.Save. More details in this answer: Where are My.Settings saved in VB 2010 .NET?
I know this question may be ridiculous but I could not find the answer. The Post sharp writes the logs in console by System.Diagnostics but I need to write the logs in a separate file. Is there any way to do so?
Thanks in advance
I found also I can do this in the app.config as the following:
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\\log.txt" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
You need to use System.Diagnostics.Trace.Listeners property to register your own listener. You would need code like this in your app's entry point:
using (StreamWriter sw = new StreamWriter("file.txt"))
using (TextWriterTraceListener tl = new TextWriterTraceListener(sw))
{
Trace.Listeners.Add(tl);
try
{
// execute your program here
}
finally
{
Trace.Listeners.Remove(tl);
}
}
My desire output is, if "rolling.log" file was created and modified by 26-06-2012, next day(27-06-2012) that file should be renamed with "rolling-26-06-2012..log". Now output is "rolling-27-06-2012.log" file.
Below is my current logging setting in web.config file.
<*loggingConfiguration name="" tracingEnabled="true" defaultCategory="myTestLog">
<*listeners>
<*add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="C:\Project\Others\Testing\testMSLogging\rolling.log"
formatter="Text Formatter" rollFileExistsBehavior="Increment"
rollInterval="Minute" rollSizeKB="50" timeStampPattern="yyMMdd"
filter="Information" />
<*add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="C:\Project\Others\Testing\testMSLogging\testMSLogging\trace.log"
formatter="Text Formatter" filter="Error" />
</listeners>
<*formatters>
<*add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.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="myTestLog">
<*listeners>
<add name="Rolling 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>
Please anyone help me. Thanks a lot.
Unfortunately this is the way it works in Enterprise Library. The philosophy behind its default flat file roller is that it records all the output in FILE.LOG and when the roll event happens, it renames it to FILE-ROLL-NAME.LOG and creates a new FILE.LOG
If you need a different behavior, you may need to create your own logging trace listener or use other tools out there like log4net.
I'm trying to write validation rules for my data objects in a WPF application. I'm writing them in the configuration file, and so far they are working fine.
I'm stumped on how to localize the messages using messageTemplateResourceName and messageTemplateResourceType. What I know is that the strings can be writen in a resource file, given a name and referenced by that name. I get the idea, but i haven't been able to make this work.
<ruleset name="Rule Set">
<properties>
<property name="StringValue">
<validator lowerBound="0" lowerBoundType="Ignore" upperBound="25"
upperBoundType="Inclusive" negated="false" messageTemplate=""
messageTemplateResourceName="msg1" messageTemplateResourceType="Resources"
tag=""
type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation"
name="String Length Validator" />
</property>
</properties>
</ruleset>
Where is the resource file and what value do I pass to messageTemplateResourceType?
I have tried writing the messages in the shell project's resource file but no sucess trying to retrieve the value. I only get the default built-in message.
I've tried
messageTemplateResourceType="typeof(Resources)"
messageTemplateResourceType="Resources"
messageTemplateResourceType="Resources.resx"
messageTemplateResourceType="typeof(Shell)"
messageTemplateResourceType="Shell"
messageTemplateResourceType="Shell,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null"
I've also tried adding a new resource file in the shell project, and adding a resource file to the data object's library. I'm all out of ideas Does anyone have any suggestions? I'm not even married to the idea of resource files, so if there are other ways to localize these messages I'd love to know!
thanks
You need to create your own resource file and then point the messageTemplateResourceType attribute to your fully qualified resource type. As long as the resource file can be loaded at runtime you should be fine.
<ruleset name="Rule Set">
...
messageTemplateResourceName="msg1"
messageTemplateResourceType="My.Fully.Qualified.ResourceType, My.AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
...
</ruleset>
An alternate way to do it would be use the messageTemplate as a key and write custom code to look up the actual localized string based on the messageTemplate key (either from a resource file or from a database or wherever else you are storing it).