Replies: 1 comment 1 reply
-
Like you mentioned you can do this manually by doing something like: [LoggerMessage(...)]
public static partial void LogSomething(this ILogger logger, int someParameter,
[CallerMemberName] string cmn = "", [CallerFilePath] string cfp = "", [CallerLineNumber] int cln = 0); This would put the values in the state without the need to modify the message template. However, you would need to do this for every source generated log message. I do agree this seems like a valid API proposal. Do you have any requirements other than the caller information be included in the log state? IMO this should be OPT-IN only and not default behavior. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
A logging system I have inherited uses
[CallerMemberName]
,[CallerFilePath]
and[CallerLineNumber]
on every log method (LogInfo, LogWarn, etc). This information is then passed to the log formatter and can be used as required.I am looking to switch to using the built-in Microsoft
ILogger
for my logging, but it is difficult to get this functionality due to the fact the log methods useparams object[]
parameters to pass in values to the message template. The[LoggerMessage]
source generator offers a solution to this issue (as well as offering many other benefits I would like to have) as I can add the caller information properties to the end of each log method, e.g.The issue now is that the message template in the
LoggerMessageAttribute
constructor arguments would need to include the format for the caller information, which I want to avoid. Rather, the caller information should be added as properties to some context (or scope) that is then later made available to the logger format engine. It can then be used however I like - e.g. a property of a log in a structured log viewer like grafana, or just used in a template when writing to a file.Now, obviously I could just write a whole new source generator that is based on the Microsoft source generator, but that does have some drawbacks. I would lose the ability to make use of future features added to the source generator, I would increase the amount of code to maintain, etc.
So before I set off writing my own source generator, I am putting the question out there: is it possible to get caller information into the state of a log event without writing a custom logging generator?
I am also aware it does not seem to be common to use these for logging, but in this case it is safe to expose this information in logs and also quite helpful for debugging. It may be removed in the future but for now it is desired as for the initial change I am seeing full feature parity with the current logger.
Beta Was this translation helpful? Give feedback.
All reactions