I am testing Debug DLLs with NUnit and it is very annoying that with every testrun a large amount of Debug Assertions come up.
So i have written a tool which is polling for a new Debug Assertion. the tool is iterating to all windows every x milliseconds and checks if the title is one of the collection of possible Debug Assertion window titles.
In pseudo code it looks like this:
void main()
{
var thread = new Thread(ThreadMethod);
thread.Start();
}
private void ThreadMethod()
{
while(true)
{
foreach(var title in possibleWindowTitles)
{
IntPtr windowHandle = FindWindowHandle(title);
if(windowHandle != IntPtr.Zero)
{
SetToForeground(windowHandle);
SendKeys.SendWait("%I);
}
}
}
}
The codeline SendKeys.SendWait("%I") sends the keycombination of ALT + I to the window, which is the keycombination for the "Continue" Button.
My Question is:
Is there a better option? something like:
An event when a new window comes up
A better method of closing the window (the CloseWindow method from the User32.dll hasn't worked for me -- no Exception, but nothing happens)
A better solution for the SetToForeGround() workaround
The best way would be an suppression of the Assertion -- Is that possible?
My way works, but i think my solution is very prone to errors. So i hole there is someone with a good idea
You can configure the behavior of the dialog box. This is a behavior provided by the DefaultTraceListener, which is configurable in code or via config file. The documentation for Debug.Assert mentions this.
In the config file, you can turn off the UI like this:
<configuration>
<system.diagnostics>
<assert assertuienabled="false" logfilename="c:\myFile.log" />
</system.diagnostics>
</configuration>
You can also just remove the default trace listener from the collection via the config file:
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<remove name="Default" />
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\myListener.log" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
Either of these can also be done via code, with the Debug.Listeners collection.
How can I define a default TraceListener, that is automatically added to all TraceSources, in a net 4.0 c# project?
Currently I have to list every named TraceSource I use in the App.config file like this:
<system.diagnostics>
<sharedListeners>
<add name="MyListener" type="MyListenerType,MyAssemblyName" />
</sharedListeners>
<sources>
<source name="Class1" switchValue="All">
<listeners><add name="MyListener"></add></listeners>
</source>
<source name="Class2" switchValue="All">
<listeners><add name="MyListener"></add></listeners>
</source>
<source name="Class3" switchValue="All">
<listeners><add name="MyListener"></add></listeners>
</source>
... repeat for a gazillion classes ...
</sources>
<system.diagnostics>
I am using a SharedListener that should receive all outputs from all TraceSources, unless otherwise specified. With the above syntax, this requires a manual entry for each TraceSource.
Whenever I introduce a new class with a new TraceSource, I have to update the App.Config. If multiple programs use that assembly, I have to update multiple App.Config. A spelling mistake while updating these entries will not produce any error, it will just silently omit all trace output from the correct source.
Is there a way I can set a default TraceListener via App.config, so that I only have to name specific TraceSources if I want to deviate from the default?
I didn't find a great solution to this, so what I did was at least centralize the creation of TraceSources. Then I can add any of the 'trace' listeners in app.config to these newly created sources:
TraceSource toReturn = new TraceSource(name, filterLevel);
//remove the default trace listener; don't 'clear' the listeners entirely, because that would undo changes made in app.config; this is a decent compromise
toReturn.Listeners.Remove("Default");
//add all global trace listeners from the app.config
toReturn.Listeners.AddRange(Trace.Listeners);
return toReturn;
Now any listeners I add to <system.diagnostics> \ <trace> \ <listeners> will be added to all trace sources I create with this code.
You could add a default listener in the machine config, but that would affect more apps than you want to affect.
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.
I came across this: Winforms logging framework
But, I cannot get it working.
In the app.config, I have the following:
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="yourName" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\mylogfile.txt" />
</listeners>
</trace>
</system.diagnostics
In my code, I have the following to write to the log file:
Trace.Write("test");
Trace.TraceError("There's been an error captain: {0}", e);
Trace.TraceWarning("The system broke but don't worry.");
Trace.TraceInformation("Starting up the engines.");
The file is created. But nothing is written to it. Trace is turned on in visual studio.
Not sure what is missing here.
You've turned off autoflush. Try setting autoflush to true or calling Trace.Flush at the end of your code sample.
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>