为C#windows应用程序创建日志文件

时间:2017-04-21 10:20:00

标签: c#

我编写了一个代码块来生成日志文件,以便我可以获取所有被调用的函数。

我使用Microsoft.Practises.EnterpriseLibrary.Logging dll获取生成的日志文件,我是否知道如何生成该文件。

string procName = "reports_plan_and_proj.plan_v_paid_inv_pay_method_sum";
Logger.Write("SQL:GetPlanvsPaidInvestPmtMthdSummary():: " + procName, "SQL");

1 个答案:

答案 0 :(得分:0)

让我们以类似的方式使用一个类

public class LogControl
{
    private static string _Path = string.Empty;
    private static bool DEBUG = true;

    public static void Write(string msg)
    {
        _Path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        try
        {
            using (StreamWriter w = File.AppendText(Path.Combine(_Path, "log.txt")))
            {
                Log(msg, w);
            }
            if (DEBUG)
                Console.WriteLine(msg);
        }
        catch(Exception e)
        {
            //Handle
        }
    }

    static private void Log(string msg, TextWriter w)
    {
        try
        {
            w.Write(Environment.NewLine);
            w.Write("[{0} {1}]", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
            w.Write("\t");
            w.WriteLine(" {0}", msg);
            w.WriteLine("-----------------------");
        }
        catch(Exception e)
        {
                        //Handle
        }
    }
}

您使用LogControl.Write("I want to log this")调用它 它产生如下输出:[1:19:34 PM Friday, April 21, 2017] I want to log this -------------