Coming from a scripting background, I’ve started working with c# and .net. I’ve created a class that creates a text file notice that a process is complete. I instantiate this class in a console application and call the write process at the end. What I’m trying to do is keep track through all my other classes when an error or warning has occurred, and reflect that event in the notice.
I’ve implemented this with public static bools, so that no matter what class is running, when a catch occurs, I can update a bool to true. I get the feeling though that this is wrong, and I don’t know enough at this point to find what I should be doing.
Can anyone help?
Code example:
namespace Logging
{
public class Notice
{
public static bool HasWarning { get; set; }
public static bool HasError { get; set; }
public string ProcessName {get; set;}
public enum Status
{
[Description("Complete Success")]
Complete_Success,
[Description("Complete with Warnings")]
Complete_With_Warnings,
[Description("Error Incomplete")]
Error_Incomplete
}
public void EndProcess(Status status)
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("{0} is Complete!", ProcessName));
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(string.Format("Completion Status: {0}", ToStringEnums(status)));
sb.Append(Environment.NewLine);
sb.Append(string.Format("Completion Time: {0}", DateTime.Now.ToString("MM/dd/yy H:mm:ss")));
File.WriteAllText(string.Format(@"{0}\EndProcess.txt", Directory.GetCurrentDirectory()), sb.ToString());
}
This is where I call it:
private static void WriteNotice()
{
Notice newNotice = new Notice();
newNotice.ProcessName = "NCOA";
if (Notice.HasError == true)
newNotice.EndProcess(Notice.Status.Error_Incomplete);
else if (Notice.HasWarning == true)
newNotice.EndProcess(Notice.Status.Complete_With_Warnings);
else
newNotice.EndProcess(Notice.Status.Complete_Success);
}
I suggest using a Try Catch statement around your code and trace like following:
for a more advanced logging mechanism i would recommend using NLOG as following: