Comparto una clase la cual sirve para crear logs de manera fácil y dinámica.
La clase crea un archivo el cual va siendo llenado por cadenas, cada mensaje es guardado en un archivo por día y al mensaje guardado se le anexa la hora en la cual fue creado.
public class Log
{
private string Path = "";
public Log(string Path)
{
this.Path = Path;
}
public void Add(string sLog)
{
CreateDirectory();
string nombre = GetNameFile();
string cadena = "";
cadena += DateTime.Now + " - " + sLog + Environment.NewLine;
StreamWriter sw = new StreamWriter(Path+"/"+nombre,true);
sw.Write(cadena);
sw.Close();
}
#region HELPER
private string GetNameFile()
{
string nombre = "";
nombre = "log_" + DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + ".txt";
return nombre;
}
private void CreateDirectory()
{
try
{
if (!Directory.Exists(Path))
Directory.CreateDirectory(Path);
}
catch (DirectoryNotFoundException ex) {
throw new Exception(ex.Message);
}
}
#endregion
}
Se utiliza de la siguiente manera:
string path = HttpContext.Current.Request.MapPath("~");
Log oLog = new Log(path);
oLog.Add("Hola mundo");