serilog not creating log files - .net-core

we are using the following piece of serilog code which writes events to console and file, the file and console logging works fine on my machine, but in the other developers machine console logging works but the file logging does not work and to add to the weirdness the"logs" folder gets created though. Is there any extra setup that needs to be done ?
public static void SetupLogger()
{
//var outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}";
var outputTemplate = "[{Level:u3}] {Message:lj}{NewLine}{Exception}";
// Logger
//var outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u4}] | {Message:l}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Console(outputTemplate: outputTemplate, theme:SystemConsoleTheme.Literate,restrictedToMinimumLevel:LogEventLevel.Information)
.WriteTo.File($"logs/log-{DateTime.Now:yyyy-MM-dd_HH:mm:ss.fff}.log")
.CreateLogger();
}

The first step when troubleshooting any issue with Serilog is to turn on the SelfLog and see if there are any exceptions being caught. The error messages might give you a clue of what's the problem.
Serilog.Debugging.SelfLog.Enable(s => Console.WriteLine($"Internal Error with Serilog: {s}"));
Alternatively, if you didn't have a Console Window, you could also use a Notepad window to inspect the SelfLog.
Anyway, are the machines where it doesn't work running Windows? I ask because looking at your code, I wouldn't expect it to work on Windows because you're saving the file with : (colon) in the name which is not a valid character for file names in Windows.

Related

How can you add :// to your file? [duplicate]

How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it?
Go to Start then in Find type regedit -> it should open Registry editor
Click Right Mouse on HKEY_CLASSES_ROOT then New -> Key
In the Key give the lowercase name by which you want urls to be called (in my case it will be testus://sdfsdfsdf) then Click Right Mouse on testus -> then New -> String Value and add URL Protocol without value.
Then add more entries like you did with protocol ( Right Mouse New -> Key ) and create hierarchy like testus -> shell -> open -> command and inside command change (Default) to the path where .exe you want to launch is, if you want to pass parameters to your exe then wrap path to exe in "" and add "%1" to look like: "c:\testing\test.exe" "%1"
To test if it works go to Internet Explorer (not Chrome or Firefox) and enter testus:have_you_seen_this_man this should fire your .exe (give you some prompts that you want to do this - say Yes) and pass into args testus://have_you_seen_this_man.
Here's sample console app to test:
using System;
namespace Testing
{
class Program
{
static void Main(string[] args)
{
if (args!= null && args.Length > 0)
Console.WriteLine(args[0]);
Console.ReadKey();
}
}
}
Hope this saves you some time.
The MSDN link is nice, but the security information there isn't complete. The handler registration should contain "%1", not %1. This is a security measure, because some URL sources incorrectly decode %20 before invoking your custom protocol handler.
PS. You'll get the entire URL, not just the URL parameters. But the URL might be subject to some mistreatment, besides the already mentioned %20->space conversion. It helps to be conservative in your URL syntax design. Don't throw in random // or you'll get into the mess that file:// is.
If anyone wants a .reg file for creating the association, see below:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\duck]
"URL Protocol"=""
[HKEY_CLASSES_ROOT\duck\shell]
[HKEY_CLASSES_ROOT\duck\shell\open]
[HKEY_CLASSES_ROOT\duck\shell\open\command]
#="\"C:\\Users\\duck\\source\\repos\\ConsoleApp1\\ConsoleApp1\\bin\\Debug\\net6.0\\ConsoleApp1.exe\" \"%1\""
Pasted that into notepad, the file -> save as -> duck.reg, and then run it. After running it, when you type duck://arg-here into chrome, ConsoleApp1.exe will run with "arg-here" as an argument. Double slashes are required for the path to the exe and double quotes must be escaped.
Tested and working on Windows 11 with Edge (the chrome version) and Chrome
There is an npm module for this purpose.
link :https://www.npmjs.com/package/protocol-registry
So to do this in nodejs you just need to run the code below:
First Install it
npm i protocol-registry
Then use the code below to register you entry file.
const path = require('path');
const ProtocolRegistry = require('protocol-registry');
console.log('Registering...');
// Registers the Protocol
ProtocolRegistry.register({
protocol: 'testproto', // sets protocol for your command , testproto://**
command: `node ${path.join(__dirname, './index.js')} $_URL_`, // $_URL_ will the replaces by the url used to initiate it
override: true, // Use this with caution as it will destroy all previous Registrations on this protocol
terminal: true, // Use this to run your command inside a terminal
script: false
}).then(async () => {
console.log('Successfully registered');
});
Then suppose someone opens testproto://test
then a new terminal will be launched executing :
node yourapp/index.js testproto://test
It also supports all other operating system.

Not able to initialize tess-two (Could not initialize Tesseract API error)

I wrote a sample Android app. I am getting 'Tesseract(native): Could not initialize Tesseract API with language=eng!' error.
I did include
compile 'com.rmtheis:tess-two:5.4.0'
in the gradle file
Also copied all 'data files' 3.04.00 version to 'tessdata' directory.
I debugged Java portion of 'init' code it seems to be working fine, it's failing inside 'nativeside'.
Any suggestions what could be going wrong with my code. Here are few lines of code I am using to init
final String lang = "eng";
TessBaseAPI baseApi = new TessBaseAPI();
File externalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String externalDirPath = externalDir.getAbsolutePath() + "/";
flag = baseApi.init(externalDirPath, lang);
The problem was not with tess-two, it was with my app, I deployed it on Marshmallow, it requires different way to get WRITE_EXTERNAL_STORAGE permission. I was not aware of it, now I fixed that issue my app is working fine.

Qt-application only works correctly if started from the command line

I made a pretty simple application with Qt Creator on Ubuntu 12.04. The application reads an xml-file and shows a couple of images. But when I try to start the application by double clicking the icon on a different machine (running Lubuntu), the images are not shown, and the xml-file is not read. The application does work properly when it is started from the command line by typing ./App.
Why does it behave like this and how do I fix it?
edit: The method that reads the xml:
QDomDocument doc("document");
QString path = "datastorage.xml"; // xml is in same directory as the executable
QFile xmlFile(path);
if (!xmlFile.open(QIODevice::ReadOnly))
throw QString("Error with XML: Could not open file " + path);
if (!doc.setContent(&xmlFile)) {
xmlFile.close();
throw QString("Error with XML: Could not set QDomDocument content from " + path);
}
xmlFile.close();
QDomElement root = doc.documentElement();
return root;
Simply you are using relative paths to read files and those paths are always relative to "working directory". If you're launching your app from console, and all required files are within app directory then everything works. When launching from desktop working directory may be different. Just prepend QCoreApplication::applicationDirPath() to all paths you're using.

log4j configuration in jar which is used by another application already using log4j

My problem is that i'm trying to set up log4j to log into a file from my jar. This jar is used by an application which already uses log4j. My jar is made as maven package shipped with log4j. I'm trying to initialize log4j from property file as such:
"log4j.properties"
log4j.appender.FileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.FileAppender.File=${user.home}/.myproject/myproject.log
log4j.appender.FileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.FileAppender.layout.ConversionPattern=%d{yy-MM-dd HH:MM:ss,SSS} [%t] %-5p %c %x - %m%n
log4j.appender.FileAppender.MaxFileSize=5MB
#myproject is full package name
log4j.logger.myproject=,FileAppender
I've included this property file into resources of my jar. I'm loading it with code:
try {
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("log4j.properties");
Properties properties = new Properties();
properties.load(inputStream);
inputStream.close();
PropertyConfigurator.configure(properties);
} catch (NullPointerException e) {
BasicConfigurator.configure();
throw new MyprojectException("log4j.properties not found", e);
} catch (IOException e) {
throw new MyprojectException("log4j.properties could not be loaded", e);
}
This code is working flawlessly when my jar is not used by an application which uses log4j. But it is, i get an empty log file or for some cases in some applications, no log file is created at all.
I've tried to add an appender manually, not with propertyconfigurator like this:
static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Myproject.class);
SimpleLayout layout = new SimpleLayout();
FileAppender appender = new FileAppender(layout,"C:/out.log",true);
logger.addAppender(appender);
logger.setLevel(Level.DEBUG);
This seems to be working fine, but i'd really want to configure log4j from properties file instead.
I've read lots of threads about how log4j handles multiple instances. I've found out that i cannot alter log4j configuration loaded by properties once it's done by one application. Some have suggested i shall ship my own log4j jar and config and configure with propertyconfigurator, that's what i've tried and as you can see it didn't work. I'm curious why my second example is working and the first is not. How can i solve this problem?
notes:
I do not want to alter the log4jconfigs of the applications that use my jar file.
I've also found out that there is -Dlog4j.configuration system property that could be used, but my jar is not an executeable jar file, it gets loaded by Class.forName
Any help is appreciated,
Thanks in advance

How to capture IIS Express output when run from Visual Studio 2010 SP1?

If you run IIS Express from the command line, anything you write Console.Out in your web app is displayed in the command line output. This is very handy for trouble shooting LINQ to SQL translation issues if you set DataContext.Log = Console.Out. However, if you check "Use IIS Express" in the web project properties in VS 2010 SP1 you never see the command line.
Can you redirect IIS Express Console.Out to a log file or something?
I found a way to write directly to the Debug Console window via damieng's blog:
class DebugTextWriter : System.IO.TextWriter {
public override void Write(char[] buffer, int index, int count) {
System.Diagnostics.Debug.Write(new String(buffer, index, count));
}
public override void Write(string value) {
System.Diagnostics.Debug.Write(value);
}
public override Encoding Encoding {
get { return System.Text.Encoding.Default; }
}
}
You can attach it to a DataContext like you would with Console.Out:
#if DEBUG
db.Log = new DebugTextWriter();
#endif
http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers
You can see console output, if you setup 'image file execution option' for iisexpress.exe. Only issue is, you will see a popup console window when a new iisexpress.exe is started. You can setup this only when you want to see console traces.
Do following to setup image file execution option:
install windbg from http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx
Setup following registry key (This link may help you http://msdn.microsoft.com/en-us/library/a329t4ed(VS.71).aspx)
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\iisexpress.exe]
"Debugger"="c:\\windbg -g -G"
You can disable image file execution option by renaming or deleting above registry key.

Resources