Skip to content

Cannot create environment variable for logging category with periods #87130

Closed
dotnet/docs
#22915

Description

@AnthonyMastrean

The logging configuration often uses namespaces (or namespace like strings, separated by periods) as category keys.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

The logging and configuration docs agree on creating environment variables for deep configuration structures.

Logging__LogLevel__Microsoft=Information

But, you can't use a period in a variable or environment variable name in any shell that I know of. It's not disallowed by the spec, apparently, but the various shells seem to avoid period in their implementations.

https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_10_02
https://tldp.org/LDP/abs/html/gotchas.html

# Logging__LogLevel__Microsoft.Hosting.Lifetime=Information
bash: Logging__LogLevel__Microsoft.Hosting.Lifetime=Information: command not found

So, how do we do this?


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Activity

  1. changed the title [-]Cannot create environment variable for namespace category with periods[/-] [+]Cannot create environment variable for logging category with periods[/+] on Feb 12, 2021
  2. adegeo commented on Feb 18, 2021

    @adegeo

    @IEvangelist @Rick-Anderson do you have an idea as to the answer? What does the environment variable system use to replace . when the setting contains a .?

  3. Rick-Anderson commented on Feb 18, 2021

    @Rick-Anderson
    Contributor

    @serpent5 can probably figure it out.

  4. serpent5 commented on Feb 18, 2021

    @serpent5
    Contributor

    The environment variable provider doesn't give special treatment to a .: It only substitutes __ for :. @Rick-Anderson and I looked into this before, but couldn't find a way to make this particular setup work. I can't see that anything has changed here, either.

  5. IEvangelist commented on Feb 18, 2021

    @IEvangelist
    Member

    While this is a good question and fair observation to call attention to it, I do not believe it is a problem. Logging is the only example that I'm aware that has namespaces or various patterns like this within their configuration settings. And since it is logging, there is no real value in keeping it a secret, or securing it away in an environment variable - you know? I'd argue that is should remain in an appsettings.json file.

  6. AnthonyMastrean commented on Feb 19, 2021

    @AnthonyMastrean
    Author

    @IEvangelist fair points... but, we're not supposed to use environment variables for secrets (and that's not the only reason they're used, see DOTNET_ENVIRONMENT and others) and we don't always have an easy way to override or provide an appsettings file (thinking some CI/CD scenarios where your "services" like linked containers syntax is limited).

  7. IEvangelist commented on Feb 19, 2021

    @IEvangelist
    Member

    I was able to set an environment variable locally in my bash environment with this name (based on this SO), it just needed quotes around it:

    env "Logging__LogLevel__Microsoft.Hosting.Lifetime=Information"

    I confirmed that I see it in the env vars too.

  8. self-assigned this
    on Feb 19, 2021
  9. AnthonyMastrean commented on Feb 19, 2021

    @AnthonyMastrean
    Author

    Good find, thanks!

  10. Rick-Anderson commented on Feb 19, 2021

    @Rick-Anderson
    Contributor

    Can you set it to

    env "Logging__LogLevel__Microsoft.Hosting.Lifetime=Error"

    and verify it's working?
    Nice work @IEvangelist

  11. IEvangelist commented on Feb 19, 2021

    @IEvangelist
    Member

    Can you set it to

    env "Logging__LogLevel__Microsoft.Hosting.Lifetime=Error"

    and verify it's working?
    Nice work @IEvangelist

    I've been testing it a lot this morning (I can confirm that does work), I'm updating the article to also include cross-plat env var setting with notes/link to the SE bits I stumbled upon. See proposed changes here.

  12. johnwc commented on Jul 3, 2022

    @johnwc

    I think this needs to be evaluated again, specifically for apps running in containers. We are not able to set an environment variable that contains a period for a container. So, we are not able to configure logging upon deployment. In our case we only want to turn on Informational logging for a specific library, so not to flood the logs.

  13. AlexandreBossard commented on Sep 27, 2022

    @AlexandreBossard

    I've ran into exactly that this morning. We have a local development setup that overrides the appsettings through environment. It works with every variables but the log levels, which is quite ridiculous. While working with containers, you want to test your environment variables does not contain typos.
    Would it be possible to translate the log levels '.' in '__' just like the ':' ?

  14. 5 remaining items

  15. LordMike commented on Mar 28, 2023

    @LordMike
    Contributor

    See also dotnet/AspNetCore.Docs#17378 - systemd also does not allow dots in env names.

  16. johnwc commented on Mar 29, 2023

    @johnwc

    @IEvangelist this issue is not resolved, I reviewed your doc update and it did not cover anything about what everyone is stating does not work. And that is, using periods in environment variable names. Surrounding the entire my.var.name=value with quotes as you describe as a workaround only works in shell environments, and not with things like Kubernetes deployments.

    @Rick-Anderson @IEvangelist can you please reopen this issue?

  17. IEvangelist commented on Mar 29, 2023

    @IEvangelist
    Member

    Hi @johnwc, Thanks for the follow-up. If that is the case, I'm not sure if this is a docs issue, it might need to get transferred to the product team if you believe that they'll need to change how env vars are parsed. Let's ask @maryamariyan, she might know.

  18. pbstrein commented on Apr 13, 2023

    @pbstrein

    We are running into a similar issue. We are running into a kubernetes environment and there is no way to configure the LogLevel for anything within a subsystem (e.g. this does not work Logging__LogLevel__System.Net.Http.HttpClient=Warning. Trying to change this value with appsettings.json requires a change that goes through the entire CICD pipeline, rather than a configuration change that can be done at runtime as needed for production debugging (i.e. temporarily changing the LogLevel of a service to get more information).

    Can this issue be re-opened?

  19. rbgarcia commented on Jun 2, 2023

    @rbgarcia

    We are also running into this issue.
    Our existing deployment strategy relies on environment variables to change the logging levels which means using appsettings.json would bring a lot more complexity into our solution. It really feels like environment variables should have a different strategy for representing . so that we can safely setup logging levels for different categories without having to worry about special characters in any of the systems that handle them.

  20. johnwc commented on Jun 3, 2023

    @johnwc

    @IEvangelist it's been a few months now with no response from @maryamariyan or product team. How can we get better attention for this issue?

  21. transferred this issue fromdotnet/docson Jun 5, 2023
  22. IEvangelist commented on Jun 5, 2023

    @IEvangelist
    Member

    Hi @johnwc and others, I transferred this issue to the dotnet/runtime repo as this is a product issue. I believe that they'll need to update the code itself to handle the desired substitution.

  23. ghost added
    untriaged
    on Jun 5, 2023
  24. tarekgh commented on Jun 9, 2023

    @tarekgh
    Member

    We are currently tracking the same issue under #35989. I will proceed to close this particular issue, but please feel free to respond here or on the linked issue if you have any further questions or require assistance.

    Please note that this is a feature request that can only be implemented in a future release. However, I can provide you with a workaround code that you can utilize in your application to temporarily resolve the issue until it is officially supported by the framework. The workaround involves creating a custom configuration provider to handle the replacement of dots in the environment variable. This workaround serves as an extension to the environment variable configuration provider, making it straightforward to implement by replacing the call to IConfigurationBuilder.AddEnvironmentVariables() with the new custom method, IConfigurationBuilder.AddCustomEnvironmentVariables().

    public class CustomEnvironmentVariablesConfigurationProvider : EnvironmentVariablesConfigurationProvider
    {
        internal const string DefaultDotReplacement = ":_";
        private string _dotReplacement; 
        public CustomEnvironmentVariablesConfigurationProvider(string? dotReplacement = DefaultDotReplacement) : base()
        {
            _dotReplacement = dotReplacement ?? DefaultDotReplacement;
        }
    
        public CustomEnvironmentVariablesConfigurationProvider(string? prefix, string? dotReplacment = DefaultDotReplacement) : base(prefix)
        {
            _dotReplacement = dotReplacment ?? DefaultDotReplacement;
        }
    
        public override void Load()
        {
            base.Load();
    
            Dictionary<string, string?> data = new Dictionary<string, string?>();
    
            foreach (KeyValuePair<string, string?> kvp in Data)
            {
                if (kvp.Key.Contains(_dotReplacement))
                {
                    data.Add(kvp.Key.Replace(_dotReplacement, ".", StringComparison.OrdinalIgnoreCase), kvp.Value);
                }
                else
                {
                    data.Add(kvp.Key, kvp.Value);
                }
            }
    
            Data = data;
        }
    }
    
    public class CustomEnvironmentVariablesConfigurationSource : IConfigurationSource
    {
        public string? Prefix { get; set; }
        public string? DotReplacement { get; set; }
    
        public IConfigurationProvider Build(IConfigurationBuilder builder)
        {
            return new CustomEnvironmentVariablesConfigurationProvider(Prefix, DotReplacement);
        }
    }
    
    public static class CustomEnvironmentVariablesExtensions
    {
        public static IConfigurationBuilder AddCustomEnvironmentVariables(this IConfigurationBuilder configurationBuilder)
        {
            configurationBuilder.Add(new CustomEnvironmentVariablesConfigurationSource());
            return configurationBuilder;
        }
    
        public static IConfigurationBuilder AddCustomEnvironmentVariables(this IConfigurationBuilder configurationBuilder, string? prefix, string? dotReplacement = CustomEnvironmentVariablesConfigurationProvider.DefaultDotReplacement)
        {
            configurationBuilder.Add(new CustomEnvironmentVariablesConfigurationSource { Prefix = prefix, DotReplacement = dotReplacement });
            return configurationBuilder;
        }
    
        public static IConfigurationBuilder AddCustomEnvironmentVariables(this IConfigurationBuilder builder, Action<CustomEnvironmentVariablesConfigurationSource>? configureSource) => builder.Add(configureSource);
    }

    Using that, now you can define the environment variable with three underscores ___ in the places you want dot.

    Logging__LogLevel__Microsoft___Hosting___Lifetime=Information    <-- Logging:LogLevel:Microsoft.Hosting.Lifetime=Information
    
  25. ghost removed
    untriaged
    on Jun 9, 2023
  26. ghost locked as resolved and limited conversation to collaborators on Jul 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions