如何在Asp.net MVC中编写日志文件

时间:2016-03-08 06:45:40

标签: asp.net-mvc

我已经为日志文件写了这个代码。但是我不知道在我的项目中使用它。

这是我的CreateLogFile.cs

class CreateLogFiles
{
    private string sLogFormat;
    private string sErrorTime;
    public CreateLogFiles()
    {
        //sLogFormat used to create log files format :
        // dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
        sLogFormat = DateTime.Now.ToShortDateString().ToString() + "" +
            DateTime.Now.ToLongTimeString().ToString() + "==>";

        //this variable used to create log filename format "
        //for example filename : ErrorLogYYYYMMDD
        string sYear = DateTime.Now.Year.ToString();
        string sMonth = DateTime.Now.Month.ToString();
        string sDay = DateTime.Now.Day.ToString();
        sErrorTime = sYear + sMonth + sDay;
    }
    public void Info(string sPathName, string sInfoMsg)
    {
        StreamWriter sw = new StreamWriter(sPathName + sInfoTime, true);
        sw.WriteLine(sLogFormat, sInfoMsg);
        sw.Flush();
        sw.Close();
    }
}

我想在我的控制器代码中使用它,但它没有显示按摩:

public ActionResult Create([Bind(Include = "LastName,FirstMidName,EnrollmentDate")] Student student)
    {
        cl.Info(Server.MapPath("/Log/LogFile.txt"),"Success");
        try
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (DataException)
        {
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        return View(student);
    }

0 个答案:

没有答案