Day 15 : 22 June 2022 : Add Settings from Environment Variables
My 100 Daze of Code
https://github.com/davidjwalling/100-days-of-code
#15 : Adding Settings from Environment Variables
So far, we've shown how program arguments can be read and applied to configure Ava settings. Now we'll look at applying setting from Environment variables. This really just makes use of the getenv function in the C library. We'll define setting names and identifiers in our namespace enumerations and const strings.
Environment variable settings will be applied before program arguments so that program arguments, which are specific to each execution of the program, can override Environment variables, which are specific to the operating context or user.
Here are the environment variable names added in the "driver" namespace. Since the Environment is not specific to the program, we prefix the settings with the program name.
Here is a new method in Driver, called GetEnvVars. It simply reads each variable and calls the appropriate method on the singleton Log instance using public functions to set appropriate values.
Note we continue to use char* for val here because getenv can return a null pointer which would throw an exception if we tried to assign that to a std::string.
In our Configure method, we add the call to GetEnvVars just before the call to GetArgVars. If a setting is defined as both an Environment variable and specific in the program arguments, the program argument value will overwrite the value from the Environment.
We'll test by adding the AVA_LOGPATH environment variable in our system.
Remember to restart Visual Studio if you're using that on Windows so that changes to the Environment will be active in your debugging session.
Now we can single-step debug to see our environment variable read and applied.
Our logging now reports the variable applied from the Environment.
And we can confirm our logs are written to the folder specific in our environment variable.







Comments
Post a Comment