Configuring custom TextWriterTraceListener to web.config - c#

I saw two answers about this topic but I can't figure out. I have a custom TextWriterTraceListener and I want it to use in my tracesource.
namespace MyTraceLogger
{
public class MyTextTraceListener : TextWriterTraceListener
{
public override void Write(string message)
{
this.Write(string.Format("{0},{1}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
message));
}
public override void WriteLine(string message)
{
this.WriteLine(string.Format("{0},{1}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
message));
}
}
}
<system.diagnostics>
<sources>
<source name="SpendingTrace" switchName="SpendingSourceSwitch" switchType="System.Diagnostics.SourceSwitch" >
<listeners>
<add name="Spending" type="MyTraceLogger.MyTraceLogger.MyTextTraceListener,MyTraceLogger.MyTraceLogger" initializeData="Spending.log" />
<remove name ="Default" />
</listeners>
</source>
</sources>
<switches>
<!-- You can set the level at which tracing is to occur -->
<add name="SpendingSourceSwitch" value="Warning" />
<!-- You can turn tracing off -->
<!--add name="SourceSwitch" value="Off" -->
</switches>
<trace autoflush="true" indentsize="4"></trace>
This is the error I get: Couldn't find type for class MyTraceLogger.MyTraceLogger.MyTextTraceListener,MyTraceLogger.MyTraceLogger.
When I right-click on MyTraceLogger's project for properties, it show assembly is MyTraceLogger and my namespace is also MyTraceLogger.

Why use configuration file and not instantiate it locally inside the code? In such way you will avoid config files being confused, moved or used incorrectly in the future development and maintenance.
Create an instance of your MyTextTraceListener and add it to trace listeners:
MyTextTraceListener myTraceListener = new MyTextTraceListener ("application.log");
Trace.Listeners.Add(myTraceListener);
Refer to this post too: How to define custom TraceListener in app.config

Why do you put the namespace twice? I think you would just need:
<add name="Spending" type="MyTraceLogger.MyTextTraceListener,MyTraceLogger" initializeData="Spending.log" />

Related

Trace does not create file for output

This is how trace listener defined in app.config:
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="Listener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Import.log" traceOutputOptions="None" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
And the simple method that calls Trace.WriteLine:
public static void WriteLine(LogLevel logLevel, string message)
{
var message = String.Format("{0}", messageText);
Trace.WriteLine(message);
}
But as a result - there is no file created and messages there. I thought that the reason could be in method that is calling outside of assembly. But that looks impossible.
Is there any additional settings that I missed? Thanks in advance.
Actually the problem was in that the static method with logging was invoking from another assembly. There are two solutions I've figured out:
Make app.config copying after build (or copy manually) to the folder with assembly which contains
that method;
Declare diagnostics section with trace options in app.config of executing assembly.

Adding a custom path for a Tracesource TextWriterTraceListener output in config

So I'm using Tracesource to log some errors and wan't to create a log file in a users local windows document structure ( something like System.Environment.SpecialFolder.LocalApplicationData ).
However I have no idea if I can do anything like that inside a config file.
<system.diagnostics>
<trace autoflush="true"/>
<sources>
<source name="MainSource"
switchName="MainSwitch"
switchType="System.Diagnostics.SourceSwitch" >
<listeners>
<add name="LogFileListener" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="LogFileListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="This is the place the output file goes to"
traceOutputOptions="ProcessId, DateTime, Callstack" />
</sharedListeners>
<switches>
<add name="MainSwitch" value="Verbose" />
</switches>
</system.diagnostics>
initializeData is I think a parameter to the constructor and is where I would have to put a custom path.
The path to the logfile in the config file is absolute and cannot be assumed by any special variables.
However, you could create it dynamically and this should solve your issue
How to: Create and Initialize Trace Sources
Below is sample code I was using for my options. It could help you understand the schema.
Configuration exeConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection diagnosticsSection = exeConfiguration.GetSection("system.diagnostics");
ConfigurationElementCollection switches = diagnosticsSection.ElementInformation
.Properties["switches"]
.Value as ConfigurationElementCollection;
foreach (ConfigurationElement switchElement in switches)
{
Debug.WriteLine("switch: name=" +
switchElement.ElementInformation.Properties["name"].Value +
" value=" +
switchElement.ElementInformation.Properties["value"].Value);
}

C# Add a footer to a trace listener when closed

How can one add a footer to a trace listener which is defined in the app.config:
<system.diagnostics>
<switches>
<!-- Set loglevel for diagnostic messages
(0=none, 1=errors, 2=warnings, 3=info, 4=verbose) -->
<add name="logLevel" value="4" />
</switches>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="FileListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="Logs\QFXLog.txt" />
<remove name="Default" />
</listeners>
</trace>
I want to write an end footer when this listener is closed.
What entries are to be defined in the config(if any?) and where must one define the footer string in code?
Thanks,
Juergen
I don't know of any way to handle this directly in the app.config file, but you could implement a class which inherits TextWriterTraceListener and then override its Close method:
namespace MyNamespace
{
public class FormattedTextTracer : TextWriterTraceListener
{
public override void Close()
{
// Write footer
Writer.WriteLine("==== Footer ====");
Writer.Flush();
base.Close();
}
}
}
And in the app.config file, replace the listener type with your class:
<listeners>
<add name="FileListener"
type="MyNamespace.FormattedTextTracer, MyNamespace"
initializeData="Logs\QFXLog.txt" />
<remove name="Default" />
</listeners>

webservices trace / log

I have set of web services and I want to add a trace layer.
I don't want to modify each web service since I have many.
I would like to write log every entering to a web service: name of web service and parameters.
What is the best way to do so?
P.S. I am using asp.net and C#.
EDIT:
I only want to wrap the web services as each one will have log(..) at the beginning.
A common way to achieve this is to inject a SOAP extension. From there you can intercept every request/response packet in raw SOAP. The sample shows how to implement one, and the explanation describes how it works and how to configure it.
Sample:
http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx
Explanation:
http://msdn.microsoft.com/en-us/library/esw638yk(vs.71).aspx
Configuration:
http://msdn.microsoft.com/en-us/library/b5e8e7kk(v=vs.71).aspx
<configuration>
<system.web>
<webServices>
<soapExtensionTypes>
<add type="{Type name}, {Assembly}" priority="1" group="0" />
</soapExtensionTypes>
</webServices>
</system.web>
</configuration>
Add a Global Application Class Global.asax file to your project and add the logging logic to the Application_BeginRequest() method. The sender object will contain the HTTP Request and parameters. You can filter for just .asmx requests and log those.
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
EDIT--
Give PostSharp a try. It's the easiest way to get this functionality. For posterity I will leave my posting below but just ignore it and use PostSharp.
If your web services are WCF then you should check out http://msdn.microsoft.com/en-us/magazine/cc163302.aspx.
At each step along the way they provide extensibility points that you can plug into. You can use these extensibility points to implement a wide variety of custom behaviors including message or parameter validation, message logging, message transformations.
No doubt this is the way to go for WCF services. Otherwise, if they are just web services then you can use the Unity framework and hookup and Interceptor to do the same thing.
If the progamming language is not important, you may put Apache Synapse as proxy in front of your services. Your clients will then send the requests to Synapse, which will delegate the requests to your original services. The proxy can be configured to do something with the requests in between, such as logging.
Please see the following links for more information:
http://synapse.apache.org/Synapse_Configuration_Language.html#proxy,
http://synapse.apache.org/Synapse_Configuration_Language.html#send,
http://synapse.apache.org/Synapse_Configuration_Language.html#log
A combination of the following examples could work for you:
http://synapse.apache.org/Synapse_Samples.html#Sample0
http://synapse.apache.org/Synapse_Samples.html#ProxyServices
e.g.:
<definitions xmlns="http://ws.apache.org/ns/synapse"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
<proxy name="StockQuoteProxy">
<target>
<endpoint>
<address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
</endpoint>
<outSequence>
<!-- log all attributes of messages passing through -->
<log level="full"/>
<!-- Send the message to implicit destination -->
<send/>
</outSequence>
</target>
<publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
</proxy>
How about writing your own HttpModule? That would negate the need to touch the existing web service code. You would just need to add your module to each web.config file.
I maintain an Open source web services framework that lets you simply achieve this by having all web services inherit from a base class and do your own logging.
Here is an example of a base-class where I maintain a distributed rolling log for all exceptions in redis - a very fast NoSQL data store:
public object Execute(TRequest request)
{
try
{
//Run the request in a managed scope serializing all
return Run(request);
}
catch (Exception ex)
{
return HandleException(request, ex);
}
}
protected object HandleException(TRequest request, Exception ex)
{
var responseStatus = ResponseStatusTranslator.Instance.Parse(ex);
if (EndpointHost.UserConfig.DebugMode)
{
// View stack trace in tests and on the client
responseStatus.StackTrace = GetRequestErrorBody() + ex;
}
Log.Error("ServiceBase<TRequest>::Service Exception", ex);
//If Redis is configured, maintain rolling service error logs in Redis (an in-memory datastore)
var redisManager = TryResolve<IRedisClientsManager>();
if (redisManager != null)
{
try
{
//Get a thread-safe redis client from the client manager pool
using (var client = redisManager.GetClient())
{
//Get a client with a native interface for storing 'ResponseStatus' objects
var redis = client.GetTypedClient<ResponseStatus>();
//Store the errors in predictable Redis-named lists i.e.
//'urn:ServiceErrors:{ServiceName}' and 'urn:ServiceErrors:All'
var redisSeriviceErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, ServiceName)];
var redisCombinedErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, CombinedServiceLogId)];
//Append the error at the start of the service-specific and combined error logs.
redisSeriviceErrorList.Prepend(responseStatus);
redisCombinedErrorList.Prepend(responseStatus);
//Clip old error logs from the managed logs
const int rollingErrorCount = 1000;
redisSeriviceErrorList.Trim(0, rollingErrorCount);
redisCombinedErrorList.Trim(0, rollingErrorCount);
}
}
catch (Exception suppressRedisException)
{
Log.Error("Could not append exception to redis service error logs", suppressRedisException);
}
}
var responseDto = CreateResponseDto(request, responseStatus);
if (responseDto == null)
{
throw ex;
}
return new HttpResult(responseDto, null, HttpStatusCode.InternalServerError);
}
Otherwise for normal ASP.NET web services frameworks I would look at the Global.asax events, specifically the 'Application_BeginRequest' event which Fires each time a new request comes in.
I don't know if this is what you are looking for ,just add this to you WCF config file after the ""
It will create very extensive logging that you will be able to read using the Microsoft Service Trace Viewer
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="ServiceModelMessageLoggingListener">
<filter type="" />
</add>
</listeners>
</source>
<source name="System.ServiceModel" switchValue="Warning, ActivityTracing"
propagateActivity="true">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="ServiceModelTraceListener">
<filter type="" />
</add>
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\ServiceLog.svclog"
type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
<filter type="" />
</add>
<add initializeData="C:\Tracelog.svclog"
type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
<filter type="" />
</add>
</sharedListeners>
</system.diagnostics>

Turning tracing off via app.config

I'm trying to use System.Diagnostics to do some very basic logging. I figure I'd use what's in the box rather than taking on an extra dependency like Log4Net or EntLib.
I'm all set up, tracing is working wonderfully. Code snippet:
Trace.TraceInformation("Hello World")
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="TraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Trace.log" traceOutputOptions="DateTime" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
and my little "Hello World" shows nicely up in my Trace.log file. But now I'd like to switch OFF tracing, so I dig into MSDN and find How to: Configure Trace Switches
. I add the <switches> element, and now my app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="TraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Trace.log" traceOutputOptions="DateTime" />
<remove name="Default" />
</listeners>
</trace>
<switches>
<add name="Data" value="0" />
</switches>
</system.diagnostics>
</configuration>
The value="0" should turn off tracing - at least if you then follow How to: Create and Initialize Trace Switches, which tells you to add this line of code:
Dim dataSwitch As New BooleanSwitch("Data", "DataAccess module")
That doesn't make sense to me: I just have to declare an instance of the BooleanSwicth to be able to manage (disable) tracing via the .config file? Should I like ... use ... the object somewhere?
Anyways, I'm sure I missed something really obvious somewhere. Please help.
How do I switch OFF tracing in app.config?
I agree with #Alex Humphrey's recommendation to try using TraceSources. With TraceSources you gain more control over how your logging/tracing statements execute. For example, you could have code like this:
public class MyClass1
{
private static readonly TraceSource ts = new TraceSource("MyClass1");
public DoSomething(int x)
{
ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x);
}
}
public class MyClass2
{
private static readonly TraceSource ts = new TraceSource("MyClass2");
public DoSomething(int x)
{
ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x);
}
}
The TraceSource.TraceEvent call will automatically check the level of the message (TraceEventType.Information) against the configured level of the associated Switch and will determine whether or not the message should actually be written out.
By using a differently named TraceSource for each type, you can control the logging from those classes individually. You could enable MyClass1 logging or you could disable it or you could enable it but have it log only if the level of the message (TraceEventType) is greater than a certain value (maybe only log "Warning" and higher). At the same time, you could turn logging in MyClass2 on or off or set to a level, completely independently of MyClass1. All of this enabling/disabling/level stuff happens in the app.config file.
Using the app.config file, you could also control all TraceSources (or groups of TraceSources) in the same way. So, you could configure so that MyClass1 and MyClass2 are both controlled by the same Switch.
If you don't want to have a differently named TraceSource for each type, you could just create the same TraceSource in every class:
public class MyClass1
{
private static readonly TraceSource ts = new TraceSource("MyApplication");
public DoSomething(int x)
{
ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x);
}
}
public class MyClass2
{
private static readonly TraceSource ts = new TraceSource("MyApplication");
public DoSomething(int x)
{
ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x);
}
}
This way, you could make all logging within your application happen at the same level (or be turned off or go the same TraceListener, or whatever).
You could also configure different parts of your application to be independently configurable without having to go the "trouble" of defining a unique TraceSource in each type:
public class Analysis1
{
private static readonly TraceSource ts = new TraceSource("MyApplication.Analysis");
public DoSomething(int x)
{
ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x);
}
}
public class Analysis2
{
private static readonly TraceSource ts = new TraceSource("MyApplication.Analysis");
public DoSomething(int x)
{
ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x);
}
}
public class DataAccess1
{
private static readonly TraceSource ts = new TraceSource("MyApplication.DataAccess");
public DoSomething(int x)
{
ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x);
}
}
public class DataAccess2
{
private static readonly TraceSource ts = new TraceSource("MyApplication.DataAccess");
public DoSomething(int x)
{
ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x);
}
}
With your class instrumented this way, you could make the "DataAccess" part of your app log at one level while the "Analysis" part of your app logs at a different level (of course, either or both parts of your app could be configured so that logging is disabled).
Here is a part of an app.config file that configures TraceSources and TraceSwitches:
<system.diagnostics>
<trace autoflush="true"></trace>
<sources>
<source name="MyClass1" switchName="switch1">
<listeners>
<remove name="Default"></remove>
<add name="console"></add>
</listeners>
</source>
<source name="MyClass2" switchName="switch2">
<listeners>
<remove name="Default"></remove>
<add name="console"></add>
</listeners>
</source>
</sources>
<switches>
<add name="switch1" value="Information"/>
<add name="switch2" value="Warning"/>
</switches>
<sharedListeners>
<add name="console"
type="System.Diagnostics.ConsoleTraceListener">
</add>
<add name="file"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace.txt">
</add>
</sharedListeners>
</system.diagnostics>
As you can see, you could configure a single TraceSource and a single Switch and all logging would occur with a single level of control (i.e. you could turn all logging off or make it log at a certain level).
Alternatively, you could define multiple TraceSources (and reference the corresponding TraceSources in your code) and multiple Switches. The Switches may be shared (i.e. multiple TraceSources can use the same Switch).
Ultimately, by putting in a little more effort now to use TraceSources and to reference appropriately named TraceSources in your code (i.e. define the TraceSource names logically so that you can have the desired degree of control over logging in your app), you will gain significant flexibility in the long run.
Here are a few links that might help you with System.Diagnostics as you go forward:
.net Diagnostics best practices?
Logging best practices
What's the best approach to logging?
Does the .Net TraceSource/TraceListener framework have something similar to log4net's Formatters?
In the links I posted, there is often discussion of the "best" logging framework. I am not trying to convince you to change from System.Diagnostics. The links also tend to have good information about using System.Diagnostics, that is why I posted them.
Several of the links I posted contain a link to Ukadc.Diagnostics. This is a really cool add on library for System.Diagnostics that adds rich formatting capability, similar to what you can do with log4net and NLog. This library imposes a config-only dependency on your app, not a code or reference dependency.
You don't turn off tracing globally this way.
You have to
1) declare a switch and set its value:
<switches>
<add name="MySwitch" value="Information"/>
</switches>
2) associate this switch with a TraceSource you use:
<sources>
<source name="MySource" switchName="MySwitch"/>
</source>
So, whatever you write via TraceSource named "MySource" is filtered according to the switch value.
If you use static methods like Trace.Write, I suppose, you cannot use switches at all, because there is no TraceSource to apply the filter.
If you want to turn off tracing by static methods, just remove all the listeners: <listeners> <clear/> </listeners>.
Check the state of dataSwitch whenever you need to log, as per:
http://msdn.microsoft.com/en-us/library/aa984285%28v=VS.71%29.aspx
However, that is pretty nasty, having to put those checks everywhere. Is their a reason you don't want to simply remove the TraceListener from the listeners collection in app.config?
Apart from that, I'd investigate using the .NET 2.0+ trace stuff which includes TraceSource. The new(er) stuff offers a much higher degree of configuration, and you might find it's more suitable.
http://msdn.microsoft.com/en-us/library/ms228993.aspx
It´s the switchValue attribute of source node:
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Off"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "somePath" />
</listeners>
</source>
</sources>
<trace autoflush="true" />
Late joining with a quick footnote about the app.config, in case this saves a couple of days from the life of someone out there:
Assume you have the startup (.exe) projectA containing classA which makes use of projectB (.dll) containing classB.
ClassB in turn makes use of a new TraceSource("classB") instance. In order to configure it you need to modify the app.config or projectA. Tweaking the app.config of projectB won't lead anywhere.
Also note that the placement of the
<system.diagnostics>
Section inside app.config seems to be causing problems if placed before the section:
<configSections>
or after the section:
<userSettings>
At least in my case, I was getting errors when I attempted to place it in these locations in the app.config of my project. The layout that worked for me was:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
...config sections here if any...
</configSections>
<system.diagnostics>
<trace autoflush="true"/>
<sources>
<source name="classB"
switchName="mySwitch"
switchType="System.Diagnostics.SourceSwitch" >
<listeners>
<clear/>
<add name="textwriterListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="ClassBLog.txt"
traceOutputOptions="DateTime" />
</listeners>
</source>
</sources>
<switches>
<add name="mySwitch" value="Verbose" />
</switches>
</system.diagnostics>
<runtime>
...runtime sections here if any...
</runtime>
<userSettings>
...usersettings sections here if any...
</userSettings>
</configuration>
Try this simple solution. In example below, "SomeNoisyLibrary" is littering the log with many useless entries. We filter them with "when condition"
https://github.com/NLog/NLog/wiki/When-Filter
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
internalLogFile="../log/MyApplication.log"
autoReload="true" throwExceptions="true">
<targets async="true">
<target xsi:type="File"
name="file"
layout="${longdate} | ${level:uppercase=true} | ${logger} | ${message} ${exception:format=ToString}"
fileName="../log/MyApplication.${processid}.${shortdate}.log" keepFileOpen="false"
maxArchiveFiles="10"
archiveAboveSize="10024000"
archiveEvery="Day"
/>
<target xsi:type="ColoredConsole"
name="console"
layout="${longdate} | ${level:uppercase=true} | ${logger} | ${message}${exception:format=ToString}" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="file,console">
<filters defaultAction='Log'>
<when condition="equals('${logger}','SomeNoisyLibrary')" action="Ignore" />
</filters>
</logger>
</rules>
</nlog>

Categories

Resources