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:
public LogEntry(string message, ErrorLogCause cause, DateTime when, object additionalInfo)
{
string excess = null;
while (message.Length > 2048)
{
excess = message.Substring(2048 - 3);
message = message.Substring(0, 2048 - 3) + "...";
if (additionalInfo == null)
{
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;
}
}
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
{
}
if (excess != null)
{
new LogEntry("...Continuation...", ErrorLogCause.Continuation, DateTime.Now, excess);
}
}