How to add filename in output command in C#

68 views Asked by At

I'm working on a group of client/server applications, who are constantly exchanging messages. In order to follow this, I've added the following line on every place a message is to be sent:

if (cfg_Following_Messages.Value != 0)
    log.Debug($"About to broadcast [{message.GetType().Name}]");
new OwnMessageHandler.BroadcastClientMessage(message).Execute();

That created a list, where I could follow all messages, being sent by the server. In top of that, as the log.Debug() is NLog related, I could also see the particular class, responsible for sending the message.

Now, there's a catch, because in the server application I'm working now, the entire application is based on one single Manager class, being spread over different files ("Manager.Order.cs", "Manager.Client.cs", ...) as follows:

File Manager.<whatever>.cs:

public partial class Manager{
...

So, even by changing the log command into:

log.Debug($"About to broadcast [{message.GetType().Name}] by [{this.GetType().Name}]");

, I still end up with something like:

2023-10-27 13:43:33.6548 | <Namespace>.Manager | About to broadcast [SpecificTypeOfMessage] by [Manager]

, which is not very useful.

I would like something like:

2023-10-27 13:43:33.6548 | <Namespace>.Manager | About to broadcast [SpecificTypeOfMessage] by [Manager.Specific.cs]

But how to do that?
This other StackOverflow post mentions things like Caller Information and StackFrame, but I prefer none of those:

  • The StackFrame solution is about getting the entire call stack, at every time a message gets sent back and forth. Although it works correctly (sf.GetFileName() is tested and yields a correct filename), it looks to me as a huge performance drop.
  • Caller Information CallerFilePath is wrong, as you can see here:

I have added , [CallerFilePath] string filePath = "" to the signature of my method, and in order only to have the filename, I've done the following:

string filename = filePath.Substring(filePath.LastIndexOf("\\") + 1);

This, however, yields Manager.cs instead of Manager.Specific.cs, so this is wrong (filePath is wrong to start with)!

Next to the fact that Caller Information's information is wrong, I also prefer not to modify the signature of my methods.

Are there other ways to log the filename?

Thanks in advance

0

There are 0 answers