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.
Related
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.
I want to delete my Nlog logfile between each application run only if it was emailed to me successfully otherwise it should keep adding to the logfile. I am using Outlook to email the file. I don't want to use Smtp since some networks block port 25 and then it does not get emailed to me.
The problem is when I try to delete the logfile with File.Delete(logfile) is says that the the file is in use by aonther process. How do I unlock or close the file in order for me to email it using Outlook (and then re-open it fo further logging)?
I was thinking of making a copy of the logfile and emailing that, but I'm not sure if its the best way to do it.
Thx for any ideas.
It's not Outlook which prevents the deletion of the file - your application is still running and logging to that file is still active, hence it is the Nlog part of your application which prevents the deletion.
Tell nlog to use a different log file, or not to log at all (you may resume logging later on).
By default nlog doesn't keep files open (file target, keepFileOpen). So either you try to delete file when your application is writing data, or outlook still using the file.
First, you may want to send it via outlook a copy of the log file. So you'd be sure that original file is not locked by an external process.
Second, you'll be able to reconfigure current file target to write to another file (log(n+1).txt or something. There are some hints about programmatic configuration at Add, enable and disable NLog loggers programmatically). So you'll be sure that application isn't logging to the file.
Then you'll be able to remove it, I think.
Option 1 :
if(chkLogger.Checked){
NLog.Config.SimpleConfigurator.ConfigureForFileLogging("Logfile.log",NLog.LogLevel.Trace);
}
else
{
NLog.Config.SimpleConfigurator.ConfigureForFileLogging("Logfile.log", NLog.LogLevel.Off);
}
Option 2 : LogManager.DisableLogging() and LogManager.EnableLogging()
from website Stopping-Starting-NLog-on-runtime
I'm setting up a dll to be used as a third party dll for a different application. I want this dll to have it's own logging so the external application doesn't have to deal with setting up anything (I don't believe they use the same logging as we do). I've read that may not be the best solution but it's the task I've been given. We want to use log4net with this. I've looked at a few of the other questions on here and they mention that it is configurable via code, however, the main issue I'm having is that there is no clear cut entry point into our code to configure log4net. I'm curious if I should just abandon having the dll configure itself and have a method that is called by the secondary application that configures the dll's logging or if there is a better way to go about this. Any input would be much appreciated
You can configure log4net programmatically. Perhaps add this code to the constructor of your DLL.
if (!log4net.LogManager.GetRepository().Configured)
{
// my DLL is referenced by web service applications to log SOAP requests before
// execution is passed to the web method itself, so I load the log4net.config
// file that resides in the web application root folder
var configFileDirectory = (new DirectoryInfo(TraceExtension.AssemblyDirectory)).Parent; // not the bin folder but up one level
var configFile = new FileInfo(configFileDirectory.FullName + "\\log4net.config");
if (!configFile.Exists)
{
throw new FileLoadException(String.Format("The configuration file {0} does not exist", configFile));
}
log4net.Config.XmlConfigurator.Configure(configFile);
}
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.
I'm trying to debug a webpart installed on a client's SharePoint instance. I wanted a quick and easy logging feature, so I thought of writing messages to a text file in the temp directory. SharePoint doesn't seem to like it, so what are my options?
IF you are writing to the temp directory, you will need to give the file (if it exists) or the directory rights for the IIS Application pool that the SharePoint IIS application is running under.
There are few ways of custom logging in sharepoint -
Use SPDiagnosticsService - You may write to the ULS via SPDiagnosticsService class.
Utilize diagnostics.asmx web service -
SharePointDiagnostics SharePointDiagnosticsObject = new SharePointDiagnostics();
SharePointDiagnosticsObject.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
string Response = SharePointDiagnosticsObject.SendClientScriptErrorReport(message, file, line, client, stack, team, originalFile);
For more details on usage of diagnostics.asmx refer the following link -
https://vivekkumar11432.wordpress.com/2016/09/23/how-to-do-logging-in-uls-from-csom-in-c/
For more details on logging refer the following link -
http://www.codeproject.com/Articles/620996/Five-suggestions-to-implement-a-better-logging-in
Don't use
Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Message");
According to Microsoft documentation - LogString is reserved for internal use and is not intended to be used directly from your code.
I would guess that this is a permissions issue that SharePoint is blocking you on (and probably not telling you that it is). When you try to write to a text file on the server, you need to have elevated permissions in order to do it. You can accomplish this using SPSecurity.RunWithElevatedPrivileges. Something like the following, if you want just a simple, small-code solution.
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (StreamWriter sw = new StreamWriter(#"C:\log.txt"))
{
//log information here
}
});
Try a logging framework like log4net, or write a small logging framework writing into an external database, you could also use lists to log if you want to stay inside sharepoint