New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is there a way to share variables inside cobra instance? #1289
Comments
Persistent flags are available to all commands. To store the logger, there's always global variables, but don't do that. I had my logger as global variable as well, but for testing it needed to be replaced with a specially prepared logger. Thus I opened the "writing to global variables" can of worms. Usually
I use zap logger, where child loggers can be easily created, including raising log level ( While this approach works for me, I would also be very interested how others solve the issue. |
I just went with this code, similar what viper does
|
If it works for you and doesn't interfere with your tests (due to First I create a special logger which records the logs:
Root logger gets set in a context which is passed to
|
This issue is being marked as stale due to a long period of inactivity |
The real problem with the context approach is that there is no API to augment the context later, we can retrieve the context in commands but not reassign. Cobra offers a lot of capabilities but the lack of a dependency injection mechanism is really a pain point. Wrappers and empty interface cannot substitute DI. |
Do you know if theres anything planned to reassign the context? Right now I have to use global variables and I don't really like that. |
There are two PRs currently under consideration for setting the context and facilitating it to be chained from prerun->run->postrun See #1551 #1118 It seems like there isn't anything new in this issue then and you can track those PRs or their underlying issues to stay abreast of that solution. Feel free to reopen this if you feel this ticket requires more discussion. |
I need to share some variables across all CMDs I use.
The problem is that one of those is logger object which supposed to change to debug mode once --debug flag is set, but that flag wont be set until PreRun()
The one option would be to use context, but of course we cant set up after we execute, so debug flag will be ignored in this case.
Help is highly appreciated
Thanks
The text was updated successfully, but these errors were encountered: