Source Code
This article provides a brief introduction to use of Caller Information as a means for creating an error logging utility class for your C# 5.0/.NET 4.5 applications. Caller Information is a new language feature introduced with the .NET 4.5 update and is made available through the System.Runtime.CompilerServices namespace.
This article provides a brief introduction to use of Caller Information as a means for creating an error logging utility class for your C# 5.0/.NET 4.5 applications. Caller Information is a new language feature introduced with the .NET 4.5 update and is made available through the System.Runtime.CompilerServices namespace.
Caller Information Attributes
There are three attributes available for use:
-
CallerMemberName
This attribute gives you the name of the caller as a string. For methods, the respective method names are returned.
-
CallerFilePath
This attribute gives you the path and file name of the source file that contains the caller.
-
CallerLineNumber
This attribute gives you the line number in the source file at which the method is called. It is important to note that the caller line number attribute points to the line where the method is called and not to the line where the exception actually occurred.
Now let see how to create common class library to write log file.
Open the Visual Studio, go to file -> Add -> New project it will the “ New Project Window”. From New project window select window from left side and Window Form Application from right side and enter “Arithmetic “ in name textbox. See fig bellow.
Let see first how to write common class library to write log file for our window form application.
For that right click solution mouse over Add then click New Project. From New Project window select Windows from left side and select Class Library. Enter Error4net in name textbox. Then click ok button.
In Error4net project you can see class1.cs file .Just delete the file. And right click on Error4net from solution explorer select Add then click class .it will open add new item window. Select class from right side and enter ErrorLog in name textbox.The Error4net project look like bellow.
Rewrite Errorlog.cs file like bellow.
using System;
using System.Runtime.CompilerServices;
using System.Configuration;
using System.IO;
namespace Error4Net
{
public static class ErrorLog
{
public static void LogInfo(string message,
[CallerMemberName] string memberName = null,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = 0)
{
string errLogFile = CreateLogFile();
if (errLogFile != string.Empty)
{
using (FileStream fs = new FileStream(errLogFile, FileMode.Append, FileAccess.Write))
{
using (StreamWriter s1 = new StreamWriter(fs))
{
s1.Write("=======================Start Info=====================" + Environment.NewLine);
s1.Write("Info: " + DateTime.Now.ToLongDateString() + Environment.NewLine);
s1.Write("Message: " + message + Environment.NewLine);
s1.Write("Caller Member Name: " + memberName + Environment.NewLine);
s1.Write("Caller Path: " + filePath + Environment.NewLine);
s1.Write("Caller Line Number: " + lineNumber.ToString() + Environment.NewLine);
s1.Write("======================End=======================" + Environment.NewLine);
}
}
}
}
public static void LogError(string message,
[CallerMemberName] string memberName = null,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = 0)
{
string errLogFile = CreateLogFile();
if (errLogFile != string.Empty)
{
using (FileStream fs = new FileStream(errLogFile, FileMode.Append, FileAccess.Write))
{
using (StreamWriter s1 = new StreamWriter(fs))
{
s1.Write("=======================Start Error=====================" + Environment.NewLine);
s1.Write("Error Log Entry: " + DateTime.Now.ToLongDateString() + Environment.NewLine);
s1.Write("Message: " + message + Environment.NewLine);
s1.Write("Caller Member Name: " + memberName + Environment.NewLine);
s1.Write("Caller Path: " + filePath + Environment.NewLine);
s1.Write("Caller Line Number: " + lineNumber.ToString() + Environment.NewLine);
s1.Write("======================End=======================" + Environment.NewLine);
}
}
}
}
private static string CreateLogFile()
{
string filepath = string.Empty;
bool IsEnableLog = false;
bool.TryParse(ConfigurationSettings.AppSettings["enablelog"].ToString(), out IsEnableLog);
if (IsEnableLog)
{
string logPath = ConfigurationSettings.AppSettings["logfile"].ToString();
filepath = Path.Combine(logPath, "logfile.txt");
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{ }
return filepath;
}
CheckFileSixe(filepath);
}
return filepath;
}
private static void CheckFileSixe(string filepath)
{
if (!File.Exists(filepath))
{
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{ }
}
else
{
long maxlogfilesize;
if (!Int64.TryParse(ConfigurationSettings.AppSettings["maxlogfilesize"].ToString(), out maxlogfilesize))
{
maxlogfilesize = 10;
}
FileInfo f = new FileInfo(filepath);
long s1 = f.Length;
if ((f.Length / 1024) >= maxlogfilesize)
{
string movefilePath = CreateOldLogFile();
File.Move(filepath, movefilePath);
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{ }
}
}
}
private static string CreateOldLogFile()
{
string logPath = ConfigurationSettings.AppSettings["logfile"].ToString();
string movelogpath = Path.Combine(logPath, "OldLog");
string moveFilepath = Path.Combine(movelogpath, "logfile" + string.Format("{0:yyyy_MM_dd_hh-mm-ss-tt}", DateTime.Now) + ".txt");
if (!Directory.Exists(movelogpath))
{
Directory.CreateDirectory(movelogpath);
}
return moveFilepath;
}
}
}
using System.Runtime.CompilerServices;
using System.Configuration;
using System.IO;
namespace Error4Net
{
public static class ErrorLog
{
public static void LogInfo(string message,
[CallerMemberName] string memberName = null,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = 0)
{
string errLogFile = CreateLogFile();
if (errLogFile != string.Empty)
{
using (FileStream fs = new FileStream(errLogFile, FileMode.Append, FileAccess.Write))
{
using (StreamWriter s1 = new StreamWriter(fs))
{
s1.Write("=======================Start Info=====================" + Environment.NewLine);
s1.Write("Info: " + DateTime.Now.ToLongDateString() + Environment.NewLine);
s1.Write("Message: " + message + Environment.NewLine);
s1.Write("Caller Member Name: " + memberName + Environment.NewLine);
s1.Write("Caller Path: " + filePath + Environment.NewLine);
s1.Write("Caller Line Number: " + lineNumber.ToString() + Environment.NewLine);
s1.Write("======================End=======================" + Environment.NewLine);
}
}
}
}
public static void LogError(string message,
[CallerMemberName] string memberName = null,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = 0)
{
string errLogFile = CreateLogFile();
if (errLogFile != string.Empty)
{
using (FileStream fs = new FileStream(errLogFile, FileMode.Append, FileAccess.Write))
{
using (StreamWriter s1 = new StreamWriter(fs))
{
s1.Write("=======================Start Error=====================" + Environment.NewLine);
s1.Write("Error Log Entry: " + DateTime.Now.ToLongDateString() + Environment.NewLine);
s1.Write("Message: " + message + Environment.NewLine);
s1.Write("Caller Member Name: " + memberName + Environment.NewLine);
s1.Write("Caller Path: " + filePath + Environment.NewLine);
s1.Write("Caller Line Number: " + lineNumber.ToString() + Environment.NewLine);
s1.Write("======================End=======================" + Environment.NewLine);
}
}
}
}
private static string CreateLogFile()
{
string filepath = string.Empty;
bool IsEnableLog = false;
bool.TryParse(ConfigurationSettings.AppSettings["enablelog"].ToString(), out IsEnableLog);
if (IsEnableLog)
{
string logPath = ConfigurationSettings.AppSettings["logfile"].ToString();
filepath = Path.Combine(logPath, "logfile.txt");
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{ }
return filepath;
}
CheckFileSixe(filepath);
}
return filepath;
}
private static void CheckFileSixe(string filepath)
{
if (!File.Exists(filepath))
{
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{ }
}
else
{
long maxlogfilesize;
if (!Int64.TryParse(ConfigurationSettings.AppSettings["maxlogfilesize"].ToString(), out maxlogfilesize))
{
maxlogfilesize = 10;
}
FileInfo f = new FileInfo(filepath);
long s1 = f.Length;
if ((f.Length / 1024) >= maxlogfilesize)
{
string movefilePath = CreateOldLogFile();
File.Move(filepath, movefilePath);
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{ }
}
}
}
private static string CreateOldLogFile()
{
string logPath = ConfigurationSettings.AppSettings["logfile"].ToString();
string movelogpath = Path.Combine(logPath, "OldLog");
string moveFilepath = Path.Combine(movelogpath, "logfile" + string.Format("{0:yyyy_MM_dd_hh-mm-ss-tt}", DateTime.Now) + ".txt");
if (!Directory.Exists(movelogpath))
{
Directory.CreateDirectory(movelogpath);
}
return moveFilepath;
}
}
}
Now let see how to use it in our window application.
Right click “Arithmetic” from solution explorer go to Add, then go to Add reference it will open Add reference window. Select Solution from right side and check Error4Net click ok
Now delete Form1.cs file from Arithmetic
Then add following line in App.config.
Now create an one simple window form ‘SimpleArithmetic.cs” like bellow
Now right click on form and click View code it will open one class file. Rewrite that file like bellow.
using Error4Net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Arithmetic
{
public partial class SimpleArithmetic : Form
{
public SimpleArithmetic()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
txtResult.Text = "";
try
{
ErrorLog.LogInfo("");
txtResult.Text = (Convert.ToInt32(txtNumber1.Text) + Convert.ToInt32(txtNumber2.Text)).ToString(); }
catch(Exception ex)
{
ErrorLog.LogError(ex.Message);
}
}
private void btnSum_Click(object sender, EventArgs e)
{
txtResult.Text = "";
try
{
ErrorLog.LogInfo("");
txtResult.Text = (Convert.ToInt32(txtNumber1.Text) - Convert.ToInt32(txtNumber2.Text)).ToString();
}
catch (Exception ex)
{
ErrorLog.LogError(ex.Message);
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Arithmetic
{
public partial class SimpleArithmetic : Form
{
public SimpleArithmetic()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
txtResult.Text = "";
try
{
ErrorLog.LogInfo("");
txtResult.Text = (Convert.ToInt32(txtNumber1.Text) + Convert.ToInt32(txtNumber2.Text)).ToString(); }
catch(Exception ex)
{
ErrorLog.LogError(ex.Message);
}
}
private void btnSum_Click(object sender, EventArgs e)
{
txtResult.Text = "";
try
{
ErrorLog.LogInfo("");
txtResult.Text = (Convert.ToInt32(txtNumber1.Text) - Convert.ToInt32(txtNumber2.Text)).ToString();
}
catch (Exception ex)
{
ErrorLog.LogError(ex.Message);
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
and rewrite program.cs file like bellow
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Arithmetic
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new SimpleArithmetic());
}
}
}
Now sample window application is ready press F5 and use this form.
No comments:
Post a Comment