Unable to generate log NLog internal logging file on Azure App Service - c#

I run websites and webjobs on Azure App Service and I want to enable NLog internal debugging to troubleshoot some logging problems. In my NLog configuration code I do:
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogFile = "nlog.txt";
When run locally during development, nlog.txt shows up in the application binary directory (bin). On Azure it does not show up. Assuming perhaps a file system permissions issue I changed the code to:
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogFile = #"d:\logfiles\nlog.txt";
Azure App Service guarantees that the d:\logfiles\ directory is writable. Yet still no nlog.txt file.
Ideas?

Actually the LogFiles folder is under D:\home in Azure (you mentioned the file path is d:\logfiles\, so I also tried to create a LogFiles folder under D: drive directly, but an 500 internal server error occurs).
Please try to change the value to d:\home\LogFiles\nlog.txt for InternalLogger.LogFile, like InternalLogger.LogFile= #"d:\home\LogFiles\nlog.txt" .
I can see the nlog.txt generated in azure by using the following code:
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogFile = #"d:\home\LogFiles\nlog.txt";
InternalLogger.Log(LogLevel.Trace, "a text message from here....");
You can refer to the pic below for test result.

Related

Azure Web App Trace logs not appearing in log

I am using Azure Web App Application Logging, and I followed the online tutorial, and made the following setup:
I get an exception and in my catch block I have the following code:
Trace.TraceError("abc");
Trace.TraceInformation("abc");
Trace.TraceWarning("abc");
Trace.WriteLine("abc");
Console.WriteLine("abc");
In the logs I get this:
2017-02-13 03:30:14 ~1ENGINEMAILERAPI GET /api/vfs/site/wwwroot/
_=1486950157594&X-ARR-LOG-ID=149fee3f-8da3-460e-816e-10e7a4b95f1d 443 - 121.121.23.217 Mozilla/5.0+(Windows+NT+6.3;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36
- https://web1.appsvcux.ext.azure.com/websites/WebsitesContent/WebsitesIndex?cacheability=3&defaultCloudName=azure&extensionName=WebsitesExtension&shellVersion=5.0.302.608%20(production%233ec7ddd.170201-1022)&traceStr=&region=southeastasia&flight=0&defaultCacheEvictionDelay=105000&websitesextension_enablemonitoringgroup=true&websitesextension_newauditlogs=true&websitesextension_resourcemenu=true&websitesextension_seetemplate=true&pageVersion=5.12.32.464175.170208-1137&l=en.en-us&trustedAuthority=portal.azure.com
enginemailerapi.scm.azurewebsites.net 200 0 0 992 1923 62
How can I get my application logging to show up?
According to the log format of error message you provided, I assumed that the log file you provided is belongs to Web Server Logs ( under /LogFiles/http/RawLogs) which formatted using W3W Logging. Based on your configuration, you have both enabled file system and blob storage for Application Logging. You could retrieve your application logs as follows:
Application Logging (Filesystem)
For a simple way, you could leverage KUDU, click "Debug console > CMD" and cd LogFiles\Application, then you could retrieve your logs as follows:
Application Logging (Blob)
You could leverage Microsoft Azure Storage Explorer to retrieve your logs as follows:
UPDATE:

Upload having errors on Appharbor. Good on Local

if (Upload.ContentLength > 0)
{
var FileName = Upload.FileName;
var path = Path.Combine(Server.MapPath("~/Content/Images"), FileName);
Upload.SaveAs(path);
cement.ImageLocation = ("/Content/Images/" + FileName);
}
This code is working perfectly in Local IIS hosting. But having problem on AppHarbor. The error that I got from the logging is this.
**Message**
An unhandled exception has occurred.
**Exceptions**
[DirectoryNotFoundException: Could not find a part of the path 'D:\Users\apphb9840cac8716388\app\_PublishedWebsites\RMQGrainsBeta\Content\Images\Capture.PNG'.]
I tried to read some of the articles about this and Got some Information that that the Folder might be protected or something, so I removed the ReadOnly on the Images folder and try to git bash, the problem is. GitBash doesn't recognize the difference and won't push the changes of the folder.
Finally got an answer from AppHarbor. So the thing is, it is not the code that is having the problem. It is the AppHarbor services that is blocking us to upload or directly access the file system. Here is what the Tech from the AppHarbor says.
About storing images: AppHarbor does not allow write access to the
application directory by default. This is because the local filesystem is
ephemeral and may be wiped on each deployment and/or during system
maintenance. For this reason it needs to be manually enabled on the
settings page, and it should only be used for temporary storage purposes such as caching.
I'd recommend using a cloud file storage solution such as Amazon S3. You can
upload files to S3 from your application or the client can upload files
directly to Amazon S3 by using presigned URLs. This will allow you to build
a scalable, distributed file storage feature that is suitable for cloud-based
platforms like AppHarbor. Let me know if you need help
implementing/architecting a solution that suits your needs!
Best,
Rune
Sorry for wasting your time Guys. But thank you for viewing the problem.

Giving Windows Service rights to move files to a remote directory that req. user/pass

I'm using EWS to grab file attachments from emails in an inbox, and need to put those files (if they meet certain criteria) onto a network directory path that requires an active directory user/pass that is not the same as what the machine running the service is using.
There's probably multiple ways to attack this. Without having to set that directory path to allow the user/pass that is running the windows service to have rights to read/write is there a way in code that I can set the user/pass before I try and place the files in that path?
In the installer setup of the windows service I've tried the following:
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User;
this.serviceProcessInstaller1.Password = "password";
this.serviceProcessInstaller1.Username = #"\\serverName\user";
when I try and install I get an error about mapping the user pass, so I tried this:
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.NetworkService;
this.serviceProcessInstaller1.Password = "password";
this.serviceProcessInstaller1.Username = #"\\serverName\user";
the installer works, the service shows up and I can start it, but when I debug/attach to the process it throws an exception when trying to write to the directory about access rights.
So maybe I'm not even attacking the right issue/section, as this is probably an active directory issue and something not done in code.
Any suggestions?
What you tried there is irrelevant to your problem.
If you're on windows 7, you may workaround by going to [Control Panel]->[User Accounts]->[Credential Manager] to store login information of target machines.

Windows service can't write to %LOCALAPPDATA%

I have built an app that works only when not run as a Windows service. Well, the service runs, but it doesn't do what it should. The service uses the Local Service account. So to kick off debugging, I thought I'd start with something simple: have it create a directory when it starts:
Directory.CreateDirectory(
Environment.SpecialFolder.LocalApplicationData + "\\MyService");
When I started the service, it stopped almost immediately and Windows reported that fact. When I commented out the above statement, recompiled and re-installed, the service ran without stopping.
Obviously the above line throws an exception of some sort. I have no way of logging the error because I can't write to the file system. Any ideas why Local Service can't create a directory in its own %LOCALAPPDATA%?
You should use GetFolderPath with LocalApplicationData like so:
string folderName = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
"MyService");
Directory.CreateDirectory(folderName)
I think this might be because there is no special folder. When running as the local service account you are running under that user, not the logged in user. so you are requesting a special folder that probably wont exist, as I don't think the local service has a profile. (I may be wrong) - I was wrong :p
Just in case anyone pops by:
C:\Windows\ServiceProfiles\LocalService
is the local service profile folder, so it will end up in there.
If you want to debug it surround that line with a try catch, and then write the error to a file:
try
{
Directory.CreateDirectory(Environment.SpecialFolder.LocalApplicationData + "\\MyService");
}
catch (Exception ex)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\MyServicelog.txt",true);
file.WriteLine(ex.Message);
file.Close();
}
At least then you can see whats causing the error
Martyn
I suggest you write the exception details to the event log. All user accounts have permission to write to the event log as long as the log and source names have already been created by an administrator (which you can do simply by running the app as yourself first).
As to the root cause of the error, it may be because LocalService doesn't normally get a full set of profile folders created by default. I'm not sure whether this is by design, or simply what I have observed on various machines.

Writing log files

I am developing c# application, which is running as a windows service.
What ever transactions we are doing in the application i am writing it into log file.
A log directory is added in app.config file as below.
<add key ="LogDir" value="log" />
<add key ="LogLevel" value="2" />
And in the c# code the above one is accessing as below.
int logLevel = Convert.ToInt32(ConfigurationManager.AppSettings["logLevel"]);
if (logLevel > 0)
{
logger = new Logger();
logger.TraceLevel = logLevel - 1;
logger.logDir = ConfigurationManager.AppSettings["logDir"];
logger.logFileBaseName = "touchserver";
}
And then when any process is happening i am writing the data to the log as below.
TouchServer.Log(Logger.MessageType.Trace, 1, "Item successfully deleted");
And when i run my application in debug mode (i mean as console application) the log file will be created in the application's debug folder and the data will write into the log file.
But my problem is that when i install my application as service the log file is not getting created in the debug folder, and i am unable to see the actions performed , in case if anything went wrong.
Please help me to find a solution in this.
And i am installing service using Installutil command.
Thanks in advance
sangita
While you could get into why this is not working and fix the solution, overall there is no need to implement a logging component.
There are excellent free libraries available that do this very well. log4net is very popular. It is easy to use, feature rich and efficient. Take a look at it.
But my problem is that when i install my application as service the log file is not getting created in the debug folder, and i am unable to see the actions performed , in case if anything went wrong.
Check out what are the result of the IO operations by using Process Monitor. I suspect you'll find the identity being used to run the service process does not have write permissions where it is trying to write the log file.
But the better option is to use an existing logging library as Hemal suggests.

Categories

Resources