Logging from ASP.NET 5 application hosted as Azure Web App

后端 未结 3 1772
刺人心
刺人心 2021-02-04 02:00

I have an ASP.NET 5 Web API that I host in Azure as a Web App. I want to log messages from my code using Azure Diagnostics. There are multiple article including Azure docs that

3条回答
  •  后悔当初
    2021-02-04 02:21

    I got Streaming Log output working for an ASP.NET 5 web app by writing the following class (based on David Ebbo's example):

    public class AzureApplicationLogTraceListener : TraceListener
    {
        private readonly string _logPath;
        private readonly object _lock = new object();
    
        public AzureApplicationLogTraceListener()
        {
            string instanceId = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID");
            if (instanceId != null)
            {
                string logFolder = Environment.ExpandEnvironmentVariables(@"%HOME%\LogFiles\application");
                Directory.CreateDirectory(logFolder);
                instanceId = instanceId.Substring(0, 6);
                _logPath = Path.Combine(logFolder, $"logs_{instanceId}.txt");
    
            }
        }
    
        public override void Write(string message)
        {
            if (_logPath != null)
            {
                lock (this)
                {
                    File.AppendAllText(_logPath, message);
                }
            }
        }
    
        public override void WriteLine(string message)
        {
            Write(message + Environment.NewLine);
        }
    }
    

    and then putting this in my Startup.Configure:

    Trace.Listeners.Add(new AzureApplicationLogTraceListener());
    

    This only supports filesystem-based logging (which is sufficient for live log streams).

提交回复
热议问题