Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am working on a windows application.

In my project I have to create a lof file for the errors which are raises while running the project.
Are the trace and debug classes of dot net framework are useful here?
Is there any other way to do this?
Posted
Updated 7-Mar-11 21:57pm
v2
Comments
Dalek Dave 8-Mar-11 3:57am    
Edited for Readability.

Really and truly, it is up to you how you do it. Sometimes, a simple text file is sufficient, other times a database table is useful.

If I am already using a database, I tend to log to a database table (or a separate database in fact) as it is simple and reliable in a multi user environment.

If not, then a text file will do fine! There is an article on Text file logging here: Create Simple Error Log Files using ASP.NET and C#[^]

Or there is my standard DB logging here:
C#
/// <summary>
/// Create a log entry in the database
/// </summary>
public LogEntry(string message, ErrorLogCause cause, DateTime when, object additionalInfo)
    {
    string excess = null;
    while (message.Length > 2048)
        {
        // Too big - truncate and add ellipsis
        excess = message.Substring(2048 - 3);
        message = message.Substring(0, 2048 - 3) + "...";
        if (additionalInfo == null)
            {
            // Great! We can save it anyway!
            additionalInfo = excess;
            excess = null;
            }
        }
    byte[] add = additionalInfo as byte[];
    AdditionalInfoType type = AdditionalInfoType.None;
    if (additionalInfo != null)
        {
        if (additionalInfo is string)
            {
            add = System.Text.Encoding.ASCII.GetBytes(additionalInfo as string);
            type = AdditionalInfoType.String;
            }
        else if (additionalInfo is byte[])
            {
            type = AdditionalInfoType.ByteArray;
            }
        else
            {
            new LogEntry("Unknown additionalInfo type supplied to LogEntry: " + additionalInfo.GetType().ToString(),
                         ErrorLogCause.ErrorInErrorReporting,
                         DateTime.Now,
                         message);
            type = AdditionalInfoType.Unknown;
            }
        }
    // Log the problem.
    string dbCon = ConfigurationManager.ConnectionStrings[dbConName].ConnectionString;
    try
        {
        using (SqlConnection con = new SqlConnection(dbCon))
            {
            con.Open();
            using (SqlCommand com = new SqlCommand("INSERT INTO SMAdmin.Log (message, loggedAt, cause, infoType, additionalInfo) " +
                                                   "VALUES (@M, @A, @C, @T, CAST(@I AS VARBINARY(MAX)))", con))
                {
                com.Parameters.AddWithValue("@M", message);
                com.Parameters.AddWithValue("@A", when);
                com.Parameters.AddWithValue("@C", cause);
                com.Parameters.AddWithValue("@T", type);
                if (add != null)
                    {
                    com.Parameters.AddWithValue("@I", add);
                    }
                else
                    {
                    com.Parameters.AddWithValue("@I", DBNull.Value);
                    }
                com.ExecuteNonQuery();
                }
            }
        }
    catch
        {
        // Anonymous catch: Error in error reporting system
        // Any attempt to record the problem will most likely makes things worse
        // as the whole system is to c**k anyway.
        }
    // Handle any extra info we couldn't fit in...
    if (excess != null)
        {
        // Problem: Issue as continuation error log and hope we can tie them together...
        new LogEntry("...Continuation...", ErrorLogCause.Continuation, DateTime.Now, excess);
        }
    }
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 8-Mar-11 3:08am    
Looks good, my 5. However your code is a bit too long to my taste. I have a shorter codes, but two instead, on two separate aspects of the problem, thanks to past Questions, please see.
--SA
OriginalGriff 8-Mar-11 3:21am    
Yeah, it is a little long because it is a generic routine which "folds" long log entries into multiple database entries if it has to. Could be a lot shorter, but then you have to restrict what can be logged - under some circumstances I don't want to do that!
Dalek Dave 8-Mar-11 3:58am    
Great Answer.
Yatin Bhagat 10-Mar-11 0:13am    
its helpful thank you so much
Ankit Choure 6-Apr-11 3:27am    
it's really nice solution.. thank you for the reply
Please see two of my past Answers on logging:

MsBuild OutPut to the TextBox on the fly in Windows Application[^]

How to create event log under a folder[^]

One Answers shows how to make a simple custom logger (you can use the standard EventLog to log in the custom sink, such as file or UI control, another one shows how to log in the System Log with custom structure (how to create a separate tree node (folder) for your applications).

Please be advised that the standard System Log is most reliable, so you should prefer it to make sure you still have a log in critical situations.

—SA
 
Share this answer
 
Comments
Dalek Dave 8-Mar-11 3:58am    
Good Links, Good Answer have a 5
Sergey Alexandrovich Kryukov 8-Mar-11 4:09am    
Thank you, Dalek,
--SA
I'm just going to mention my weapon of choice - log4net[^]

The most useful part about log4net is with the same codebase, you can drive multiple appenders by simply adding a few configuration entries

For examples

C#
if (log.IsInfoEnabled)
{
    log.Info("Some information message to write to the log file");
}


After that, you can specifiy appenders in your config file.

e.g 'Append to SQL Server', 'Append to text file', 'Append to UDP port'

Appender Examples[^]

So that line of code will append to as many targets as you configure. With absolutely no change to your code, you can append log information to various locations

I find log4net quite simple to work with & the options are really useful...I'm using it in some large production systems with no problems
 
Share this answer
 
v2
Comments
zingoraa 23-Mar-11 8:08am    
good tool, its available in java too.
C#
private static void _WriteError(string pError)
{
    System.IO.StreamWriter logger = null;
    if (!System.IO.Directory.Exists(ApplicationPath + @"\Log"))
    {
        System.IO.Directory.CreateDirectory(ApplicationPath + @"\Log");
    }

    logger = new System.IO.StreamWriter(ApplicationPath + @"\Log\" + Application.ProductName, ".log"), true);
    logger.Write(Environment.NewLine);
    logger.Write(pError);
    logger.Flush();
    logger.Close();
    logger = null;
}
 
Share this answer
 
you can manage by exception handling like below
try
{ 
  Statement 1.// which will be error occur 
}
 catch ( exception ex) // Object of Exception 
 {
   //manages or create the txt file and thn send it you mail id 
}
 
Share this answer
 
v2
Comments
Dalek Dave 8-Mar-11 3:59am    
At least put it in a code block for readability.
we can also manage though the database ....whenever error occur catch it by exception heading and insert into database in every time and end of the date it send in you mail id...if data exist in your table in current date...please let me its right way..
sorry for poor English ....
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900