How to Run a windows service as console application on client machine - c#

I have a self hosted windows service application with output type as Console application. I have added some console logs in that service. I need to view those logs in console window, without writing log file in local.

Use the Debug.WriteLine in your code and view all these Strings using the DbgView and this will not need the Console to be open.
Simple as
System.Diagnostics.Debug.WriteLine("Your Debug String Here");

this i how I do it
#if DEBUG
var log = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.WriteTo.Console()
.MinimumLevel.Debug()
.CreateLogger();
#else
var log = new LoggerConfiguration().ReadFrom.Configuration(config).CreateLogger();
#endif

Related

How to create a serilog logger file using docker in C# console Application with .Net3.1

I want to create serilog logger file using docker image. I am able to create a file in console app but not able to create using docker.
Here is my sample code,
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File(fileName, rollingInterval: RollingInterval.Day)
.WriteTo.File(#"C:\log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
In short, the docker idea is to isolate the application from the host it is running on. Your app is trying to access the 'c:\log.txt' file which resides on host, not the container. You can write to the file inside the container by specifying the path like '/app/log.txt' (note the linux-style).
If you really need the host-side log file, the more complicated approaches are required - this SO answer may help:
Expose log file outside docker container

Serilog WriteTo.File with C# UWP

I am writing an uwp app with C# and I would like to use serilog to write logfiles.
When I do it in a .NET Core Console application it creates the file with the wanted content.
In the uwp I can show the log messages on the GUI, but no log file is created (yes, I have broadFileSystemAccess).
My code:
Log.Logger = new LoggerConfiguration().WriteTo.File("log.txt").CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();
I would expect that it creates log.txt file in the directory which can be get with Windows.Storage.ApplicationData.Current.LocalFolder like
storageFolder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
does.
Can anyone tell me what I have to change or to consider to log to a file with serilog in my uwp app?
One of the great things about Serilog is that it's open-source and you can look at its source code and see what it is doing / how it works.
If you peek at the source code of the File sink, you'll notice that it is simply opening a file via System.IO.File.Open on the same folder where your app is running, which running from Visual Studio is probably going to be something like C:\Users\augustoproiete\MyApp\MyUwpApp\bin\x64\Debug\AppX\ where you don't have access to write file.
That means you have to be explicit about where to store the file, for example in the application data folder of your app. E.g.:
var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt");
Log.Logger = new LoggerConfiguration().WriteTo.File(logFilePath).CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();
I'd recommend you read the Debugging and Diagnostics page on Serilog's docs, as it explains how you see error messages from Serilog - which you'd have seen that it was failing to create a file and the path it was using.
Thank yu for your answer!
I thought that the local folder path is automatically used, so I did not try that.
I jus had to modify the code as follows
var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose() //otherwise Debug is not logged
.WriteTo.File(logFilePath)
.CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();
then it woked and wrote the Debug message to the log file :)
Thank you very much!

Email the Log file created at the end of Program using Serilog

I am using Serilog library in a C# Console Application to build a Scheduler, which logs messages in a Log File for each day. The filenames are created dynamically using below code.
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs\\log-scheduler-.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
How can I get to know the Name of File that my Console application has created? At the end of my program, I want to email the log file as attachment.
Serilog doesn't expose a way to inspect the name of the file(s) that were created, as of this writing.
If you don't use a RollingInterval and have the log messages be written to a single file, then you know exactly what the name of the file is, because you already specified it in the log pipeline configuration: logs\\log-scheduler-.txt.
But if you want to use a RollingInterval then you what you could do, is to inspect the folder where your log files are being written to, and find the log file(s) that were updated since your application started, by capturing the current timestamp when your app starts, and then looking at the LastWriteTimeUtc attribute of the log files in the file system to see anything that has changed since that time.
e.g.
DateTime appStartTime = DateTime.UtcNow;
// ... (app code)
// Ensure that all messages are flushed to the file
Log.CloseAndFlush();
// Get all log files modified since the app started
var logFilesUpdatedInThisSession = new DirectoryInfo(#"C:\Temp\logs\")
.EnumerateFileSystemInfos("log-scheduler-*.txt")
.Where(f => f.LastWriteTimeUtc >= appStartTime)
.OrderBy(f => f.LastWriteTimeUtc)
.ToList();
if (logFilesUpdatedInThisSession.Any())
{
// Send all files via e-mail ...
}
Another alternative (better IMO) would be to not send e-mails at all from your app, and just ship the logs to a server, such as a Seq server which allows you to easily browse the logs, apply filters, etc., which is a much better experience than opening a log file attached to an e-mail on a text editor.

Windows C# Console Application Through Task Scheduler Won't Run Unless User Is Logged In

The environment is Windows Server 2016 Standard, using a C# Console Application developed in Visual Studio 2019 and published via the VS2019 Publish Wizard. The weird thing is this seemed to work fine on our old instance of Windows Server 2008, but has not worked properly since we upgraded to 2016.
I've developed a C# Console Application to add data to my SQL Server database. It is published and running directly on the DB server using Task Scheduler. If I'm logged in when the scheduled task runs, no problems. But if I am not logged in, the console application does not run and I'm having trouble seeing how far it even gets.
Any advice on how to get this to run with a non-logged in user, or how to better troubleshoot where the hold-up is would be greatly appreciated.
Currently as a test, all I am trying to do is start the app, write to the event viewer application log and to a text file (neither happen unless logged in).
static void Main()
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string status = "Start: " + DateTime.Now.ToString() + "...";
Log(status);
status = "Complete: " + DateTime.Now.ToString() + ". Press Enter to exit.";
Log(status);
}
public static void Log(string message)
{
// Create a writer and open the file:
StreamWriter log;
string LogFilePath = "C:\\[folder]\\LogFile.txt";
if (!File.Exists(LogFilePath))
{
log = new StreamWriter(LogFilePath);
}
else
{
log = File.AppendText(LogFilePath);
}
// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(message);
log.WriteLine();
// Close the stream:
log.Close();
Console.WriteLine("-Log Entry Added");
}
Interestingly, I do see a ClickOnce process added to the Task Manager when I run as a non-logged in user, but still doesn't work appropriately.
Here are some of the things I've tried so far:
Run as my own domain account, system and as a local administrator account
Call a .bat file with the following command to open the console application: "START /B "Name" CMD /c "E:\setup.exe"" The call to the .bat file works but the Console Application does not run properly
Call setup.exe or ConsoleApplication.application directly from task scheduler
Changing the output type from "Console Application" to "Windows Application"
Below are screenshots to show my selected settings in Task Scheduler:
Something that fixed my problem: I re-created the console application from scratch, but created using .NET Core 3.0 framework. Copied my code in and re-added packages. I then published this new application to the server and it worked as expected. Still not sure what to attribute this to, but this fixed my issue

WCF REST Service Console Host

I have a c# REST webservice that has a console host for debugging purposes. I need to add authentication mode to this service, my console host code looks like this:
WebServiceHost host = new WebServiceHost(typeof(WebService,new Uri[] { new(http://localhost:8000/")});
WebHttpBinding binding = new WebHttpBinding();
host.AddServiceEndPoint(typeof(WebService, binding, "");
host.Open();
Console.WriteLine("Testing Webservice through console. Press Enter to quit.");
Console.ReadLine();
host.Close(System.TimeSpan.Zero);
The authentication in web.config can be added by:
<system.web><authentication mode="Windows"/></system.web>
How can i add authentication mode to my console host?
When an application is running in IIS, it uses web.config to store settings. When you have a desktop application (ie a console app like yours), the same settings are stored in App.config.
Just go to 'Add New Item' and select 'Application Configuration File'. This will create an App.config file in your project, which is where you can put the WCF configuration.

Categories