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
If you look at your web.config
, it probably has stdoutLogEnabled="false"
. If you set that to true, then anything that is written to standard output will be written to a file. And the stdoutLogFile
determines where it goes, which by default is under d:\home\logfiles
.
Now you need to make sure that your logging actually goes to stdout. Doing Console.WriteLine
would definitely work. I think it's probably possible to also configure things via ILoggerFactory
in your startup.cs
to make logs go to stdout.
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).
I've found an simple trick for azure app ,see https://github.com/aspnet/Logging/tree/dev/src/Microsoft.Extensions.Logging.AzureAppServices, please add the package "Microsoft.Extensions.Logging.AzureAppServices": "1.0.0-preview1-final" and update related dependencies, add the azure diagnostics in startup.cs like this :
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddAzureWebAppDiagnostics(); // for default setting.
or for custom setting:
loggerFactory.AddAzureWebAppDiagnostics(new AzureAppServicesDiagnosticsSettings( ...)); // add custom setting.
// see here for detailed member properties: https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Extensions.Logging.AzureAppServices/AzureAppServicesDiagnosticsSettings.cs
And enable the diagnostics log on azure, both logging on blob and file are work well. No need for any extra configuration. :)