473,803 Members | 4,391 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing Assertions to a log file?

I'd like to use Debug.Assert() but output to a log file instead of the
popup window. Can some one provide an example of how that is done? Or
will C# only let you use th popup window?

Thanks,
Brett

Sep 25 '06 #1
8 3431
Brett Romero wrote:
I'd like to use Debug.Assert() but output to a log file instead of the
popup window. Can some one provide an example of how that is done? Or
will C# only let you use th popup window?

Thanks,
Brett
http://msdn2.microsoft.com/en-us/library/ty5e4c4h.aspx
http://msdn2.microsoft.com/en-us/library/76dt1k3h.aspx

HTH,
Andy
--
You can email me directly by removing the NOSPAm below
xm**********@gm xNOSPAm.netNOSPAm
Sep 25 '06 #2
Thanks. This gives output similar to:

---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
b.Equals(0): False
---- Assert Long Message ----

at Startup.UT() C:\Test\TestCon sole\Main.cs(27 )
at Startup.Main(St ring[] args) C:\Test\TestCon sole\Main.cs(18 )
at AppDomain.nExec uteAssembly(Ass embly assembly, String[] args)
at AppDomain.Execu teAssembly(Stri ng assemblyFile, Evidence
assemblySecurit y, String[] args)
at HostProc.RunUse rsAssembly()
at ThreadHelper.Th readStart_Conte xt(Object state)
at ExecutionContex t.Run(Execution Context executionContex t,
ContextCallback callback, Object state)
at ThreadHelper.Th readStart()

Is there a way to just output just this part:

---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
b.Equals(0): False
---- Assert Long Message ----

at Startup.UT() C:\Test\TestCon sole\Main.cs(27 )
at Startup.Main(St ring[] args) C:\Test\TestCon sole\Main.cs(18 )

The other information is useless to me. The message, file, and a line
number with current code and caller is all I need.

Thanks,
Brett

Sep 25 '06 #3
Brett Romero wrote:
Thanks. This gives output similar to:

---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
b.Equals(0): False
---- Assert Long Message ----

at Startup.UT() C:\Test\TestCon sole\Main.cs(27 )
at Startup.Main(St ring[] args) C:\Test\TestCon sole\Main.cs(18 )
at AppDomain.nExec uteAssembly(Ass embly assembly, String[] args)
at AppDomain.Execu teAssembly(Stri ng assemblyFile, Evidence
assemblySecurit y, String[] args)
at HostProc.RunUse rsAssembly()
at ThreadHelper.Th readStart_Conte xt(Object state)
at ExecutionContex t.Run(Execution Context executionContex t,
ContextCallback callback, Object state)
at ThreadHelper.Th readStart()

Is there a way to just output just this part:

---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
b.Equals(0): False
---- Assert Long Message ----

at Startup.UT() C:\Test\TestCon sole\Main.cs(27 )
at Startup.Main(St ring[] args) C:\Test\TestCon sole\Main.cs(18 )

The other information is useless to me. The message, file, and a line
number with current code and caller is all I need.

Thanks,
Brett
Here is some sample code:

using System.Diagnost ics;
using System.IO;

namespace ConsoleApplicat ion
{
public class LogListener : DefaultTraceLis tener
{
public override void Fail(string message, string detailMessage)
{
// needs to pop up UI
if(AssertUiEnab led)
base.Fail(messa ge, detailMessage);

// is a log file configured??
if (LogFileName == null
|| LogFileName == string.Empty)
return;

using (StreamWriter logFile =
new StreamWriter(Lo gFileName, true))
{
StackTrace stack = new StackTrace();
StackFrame[] frames = stack.GetFrames ();

// extract and log what you need....
logFile.WriteLi ne(stack);
}
}
}
class Program
{
static void Main(string[] args)
{
Debug.Assert(fa lse, "BOOM");
}
}
}

By using the following app.config aou can inject your implemetation:

<?xml version="1.0" encoding="utf-8" ?>
<configuratio n>
<system.diagnos tics>
<trace autoflush="true " indentsize="0">
<listeners>
<clear />
<!--Use full qualified type name-->
<add
name="LogListen er"
type="ConsoleAp plication.LogLi stener, ConsoleApplicat ion"
/>
</listeners>
</trace>
<assert assertuienabled ="false" logfilename="c: \log.txt"/>
</system.diagnost ics>
</configuration>

HTH,
Andy
--
You can email me directly by removing the NOSPAm below
xm**********@gm xNOSPAm.netNOSPAm
Sep 25 '06 #4
Thanks. I'm guessing if I want to clear the log file before each
execution of the app, I'll need to add that to the LogListener class?

Brett

Sep 25 '06 #5
....and the link that tells you to override TraceListener.F ail() and other
details is http://msdn2.microsoft.com/en-us/library/ttcc4x86.aspx
"Andreas Mueller" <me@privacy.net wrote in message
news:4n******** ****@individual .net...
Brett Romero wrote:
>Thanks. This gives output similar to:

---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
b.Equals(0): False
---- Assert Long Message ----

at Startup.UT() C:\Test\TestCon sole\Main.cs(27 )
at Startup.Main(St ring[] args) C:\Test\TestCon sole\Main.cs(18 )
at AppDomain.nExec uteAssembly(Ass embly assembly, String[] args)
at AppDomain.Execu teAssembly(Stri ng assemblyFile, Evidence
assemblySecuri ty, String[] args)
at HostProc.RunUse rsAssembly()
at ThreadHelper.Th readStart_Conte xt(Object state)
at ExecutionContex t.Run(Execution Context executionContex t,
ContextCallbac k callback, Object state)
at ThreadHelper.Th readStart()

Is there a way to just output just this part:

---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
b.Equals(0): False
---- Assert Long Message ----

at Startup.UT() C:\Test\TestCon sole\Main.cs(27 )
at Startup.Main(St ring[] args) C:\Test\TestCon sole\Main.cs(18 )

The other information is useless to me. The message, file, and a line
number with current code and caller is all I need.

Thanks,
Brett

Here is some sample code:

using System.Diagnost ics;
using System.IO;

namespace ConsoleApplicat ion
{
public class LogListener : DefaultTraceLis tener
{
public override void Fail(string message, string detailMessage)
{
// needs to pop up UI
if(AssertUiEnab led)
base.Fail(messa ge, detailMessage);

// is a log file configured??
if (LogFileName == null
|| LogFileName == string.Empty)
return;

using (StreamWriter logFile =
new StreamWriter(Lo gFileName, true))
{
StackTrace stack = new StackTrace();
StackFrame[] frames = stack.GetFrames ();

// extract and log what you need....
logFile.WriteLi ne(stack);
}
}
}
class Program
{
static void Main(string[] args)
{
Debug.Assert(fa lse, "BOOM");
}
}
}

By using the following app.config aou can inject your implemetation:

<?xml version="1.0" encoding="utf-8" ?>
<configuratio n>
<system.diagnos tics>
<trace autoflush="true " indentsize="0">
<listeners>
<clear />
<!--Use full qualified type name-->
<add
name="LogListen er"
type="ConsoleAp plication.LogLi stener, ConsoleApplicat ion"
/>
</listeners>
</trace>
<assert assertuienabled ="false" logfilename="c: \log.txt"/>
</system.diagnost ics>
</configuration>

HTH,
Andy
--
You can email me directly by removing the NOSPAm below
xm**********@gm xNOSPAm.netNOSPAm

Sep 25 '06 #6
Brett Romero wrote:
Thanks. I'm guessing if I want to clear the log file before each
execution of the app, I'll need to add that to the LogListener class?

Brett
Yeah, that should be a good place:

using System.Diagnost ics;
using System.IO;

namespace ConsoleApplicat ion
{
public class LogListener : DefaultTraceLis tener
{
private static bool initialized = false;
public override void Fail(string message, string detailMessage)
{
if(!initialized )
{
if(File.Exists( LogFileName))
File.Delete(Log FileName);
initialized = true;
}
// needs to pop up UI
if(AssertUiEnab led)
base.Fail(messa ge, detailMessage);

// is a log file configured??
if (LogFileName == null
|| LogFileName == string.Empty)
return;

using (StreamWriter logFile =
new StreamWriter(Lo gFileName, true))
{
StackTrace stack = new StackTrace();
StackFrame[] frames = stack.GetFrames ();

// extract and log what you need....
logFile.WriteLi ne(stack);
}
}
}
class Program
{
static void Main(string[] args)
{
Debug.Assert(fa lse, "BOOM");
Debug.Assert(fa lse, "BOOM");
}
}
}
HTH,
Andy
--
You can email me directly by removing the NOSPAm below
xm**********@gm xNOSPAm.netNOSPAm
Sep 27 '06 #7
Andreas, what is needed to actually use the custom listener class?
When I call Debug.Assert(), it isn't using the custom listener. I say
that because the log is not cleared and break points in the class
aren't hit.

Thanks,
Brett

Sep 28 '06 #8
Sorry, I didn't have the listeners section configured in the config
file.

Brett

Sep 29 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

40
4286
by: post400 | last post by:
Hi, there is another famous book 'Writing solid code' but does it apply to Python ? Or it's usable only by Microsoft C programmers ? The author seems to be an ex-Microsoft guy ! Thanks , post400
0
290
by: P. Chalin | last post by:
If you make use of assertions (e.g. assert statements) in your code, I would like to invite you to participate in a 15 min survey on program assertions. In this survey we seek your opinion concerning the issue of errors/exceptions raised during assertion evaluation. The questionnaire is available here: https://www.dsrg.org/ASN_Survey/wnd.html Thank-you in advance, P.Chalin
9
2939
by: 100 | last post by:
Has anybody read Steve Maguire's book "Writing solid code"? Do you think that the ideas in this book are not applicable in c# language? Does anybody find if(2 == i) istead of if(i == 2) as unnetural and does it lead to more bugs in the code because of it makes programms hard to read. And my last question is: "Do you think that using boolean expressions
14
1720
by: Divick | last post by:
Hi, is it a nice idea to do assetion checks for method arguments ? I am currently redesigning a piece of code. Now the problem is that there are some assumptions for the method arguments that the code makes. It is not checking the validity of the arguments everywhere because that would lead to performance penalty. So I am think that at least assertions will be able check the arguments at least for debug version to verify the design. But...
8
2042
by: Jefffff | last post by:
Regarding the use of assertions: According to Juval Lowy's excellent coding standards document (PDF download available at www.idesign.net), every assumption in your code should have an assertion... and on average, every 5th line is an assertion. My question: Do any of you include that many assertions? I agree in principle that we should code defensively, but his recommendation just seems to go "overboard" and would result in a lot of...
8
528
by: priyanka | last post by:
Hi there, Can anyone show me how the assert() function works ? I need to develop my own assert() function instead of using the one defined in the assert.h file. It would be great if anyone could show me the actual source code of assert() function in assert.h header file. I need to write the assert function that prints out error message when the expression is wrong. For eg.,
58
3101
by: jeffc226 | last post by:
This might be less of a design issue than a C++ language issue per se, but I have a problem with assertions. I mean, they work, of course. But there's something I'm uncomfortable with that's never been explained to my satisfaction. I recently read this explanation. "There is an effective litmus test to differentiate the cases in which you need to use assert and when you need to use genuine error checking: you use error checking for...
1
1741
by: =?iso-8859-1?Q?Daniel_Lidstr=F6m?= | last post by:
(I posted this to m.p.pocketpc.developer but got no answers) Hello! I have a problem when launching my application. It starts with firing an assertion. This assertion is inside mfc or atl it seems, and the message is the following: Debug Assertion Failed!
3
1665
by: Hugh Oxford | last post by:
I am told that I should use assertions in my testing. The problem is, because I test using a cut of live data, the data always changes. Has anyone come up against this or have they abandoned assertions generally? On a more general note, how does one reconcile a changing data set with testing driven development?
0
9699
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10542
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10309
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10289
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7600
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6840
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5496
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4274
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2968
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.