C# : Write error log in text file
How to write error in text file. Where we can set configuration that we want to write or not, without editing code file.
Create service signature using interface.
public static void WriteLog(string LogValues) {
try { if (!Convert.ToBoolean(ConfigurationManager.AppSettings["writelog"].ToString())) return;
// for web application //var folder = System.Web.HttpContext.Current.Request.PhysicalApplicationPath.ToString() + "\\ErrorLog\\";
//For Static path
var folder = ConfigurationManager.AppSettings["LogPath"].ToString();
if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var fileName = DateTime.Today.ToString("dd-MMM-yy", CultureInfo.InvariantCulture) + ".txt"; var serverPath = folder + fileName; if (!File.Exists(serverPath)) { File.Create(serverPath).Close(); } var w = File.AppendText(serverPath); try { w.WriteLine("\n" + System.DateTime.Now + "\t" + LogValues); w.Flush(); w.Close(); } catch { } finally { w.Close(); } } catch (Exception ex) { } }
Set configuration in web.config file.
<add key="writelog" value="true" /> <add key="logpath" value="D:\ErrorLog\" />
Enjoy to write error log in text file, trace issue and give solution.