You need to ensure that only one thread is writing to the file. If you have 2 concurrent users calling the Index action at the same time chances are they will try to write to the log file at the same time and the second will fail. In a multithreaded applications such as ASP.NET always make sure that you are properly synchronizing access to shared resources.
Also in your code you are not guarding against errors. What if an exception is thrown? You never close this stream and the second attempt to access it will throw an exception.
So one possibility to simplify this code is to use the TPL:
private static object _synRoot = new object();
public ActionResult Index()
{
Task.Factory.StartNew(() =>
{
lock (_synRoot)
{
var data = string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine)
System.IO.File.AppendAllText("log.txt", data);
}
});
return View();
}
and to avoid such noise and pollution in your controllers you could use action filters:
public class LogAttribute : ActionFilterAttribute
{
private static object _synRoot = new object();
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Task.Factory.StartNew(() =>
{
lock (_synRoot)
{
var data = string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine)
System.IO.File.AppendAllText(@"log.txt", data);
}
});
}
}
and then:
[Log]
public ActionResult Index()
{
return View();
}
But instead of reinventing wheels I would recommend you using the tracing capabilities built into the .NET framework.