{"id":20905243,"url":"https://github.com/akkadotnet/akka.hosting","last_synced_at":"2025-04-07T16:18:21.551Z","repository":{"id":37773181,"uuid":"466519025","full_name":"akkadotnet/Akka.Hosting","owner":"akkadotnet","description":"Akka.Hosting - standardized Akka.NET hosting without any HOCON configuration. Ties into Microsoft.Extensions.Configuration, Logging, Hosting, and DependencyInjection.","archived":false,"fork":false,"pushed_at":"2024-03-14T18:07:22.000Z","size":732,"stargazers_count":46,"open_issues_count":10,"forks_count":11,"subscribers_count":9,"default_branch":"dev","last_synced_at":"2024-03-26T15:56:47.699Z","etag":null,"topics":["actor-model","actors","akkadotnet","ihostedservice"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/akkadotnet.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2022-03-05T17:16:01.000Z","updated_at":"2024-06-04T23:00:17.596Z","dependencies_parsed_at":"2023-09-27T00:06:43.826Z","dependency_job_id":"649d7874-47b9-4b4c-91f5-0d43a4a7edb0","html_url":"https://github.com/akkadotnet/Akka.Hosting","commit_stats":null,"previous_names":[],"tags_count":66,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akkadotnet%2FAkka.Hosting","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akkadotnet%2FAkka.Hosting/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akkadotnet%2FAkka.Hosting/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akkadotnet%2FAkka.Hosting/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/akkadotnet","download_url":"https://codeload.github.com/akkadotnet/Akka.Hosting/tar.gz/refs/heads/dev","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247685628,"owners_count":20979085,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["actor-model","actors","akkadotnet","ihostedservice"],"created_at":"2024-11-18T13:23:36.262Z","updated_at":"2025-04-07T16:18:21.534Z","avatar_url":"https://github.com/akkadotnet.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ca id=\"akkahosting\"\u003e\u003c/a\u003e\n# Akka.Hosting\n\nHOCON-less configuration, application lifecycle management, `ActorSystem` startup, and actor instantiation for [Akka.NET](https://getakka.net/).\n\nSee the [\"Introduction to Akka.Hosting - HOCON-less, \"Pit of Success\" Akka.NET Runtime and Configuration\" video](https://www.youtube.com/watch?v=Mnb9W9ClnB0) for a walkthrough of the library and how it can save you a tremendous amount of time and trouble.\n\n# Table Of Content\n\n- [Supported Packages](#supported-packages)\n    * [Akka.NET Core Packages](#akkanet-core-packages)\n    * [Akka Persistence Plugins](#akka-persistence-plugins)\n    * [Akka.HealthCheck](#akkahealthcheck)\n    * [Akka.Management Plugins](#akkamanagement-plugins)\n        + [Akka.Management Core Package](#akkamanagement-core-package)\n        + [Akka.Discovery Plugins](#akkadiscovery-plugins)\n        + [Akka.Coordination Plugins](#akkacoordination-plugins)\n- [Summary](#summary)\n- [Dependency Injection Outside and Inside Akka.NET](#dependency-injection-outside-and-inside-akkanet)\n    * [Registering Actors with the `ActorRegistry`](#registering-actors-with-the-actorregistry)\n    * [Injecting Actors with `IRequiredActor\u003cTKey\u003e`](#injecting-actors-with-irequiredactortkey)\n    * [Resolving `IRequiredActor\u003cTKey\u003e` within Akka.NET](#resolving-irequiredactortkey-within-akkanet)\n- [Microsoft.Extensions.Configuration Integration](#microsoftextensionsconfiguration-integration)\n    * [IConfiguration To HOCON Adapter](#iconfiguration-to-hocon-adapter)\n- [Microsoft.Extensions.Logging Integration](#microsoftextensionslogging-integration)\n    * [Logger Configuration Support](#logger-configuration-support)\n    * [Microsoft.Extensions.Logging.ILoggerFactory Logging Support](#microsoftextensionsloggingiloggerfactory-logging-support)\n    * [Serilog Support](#serilog-support)\n    * [Microsoft.Extensions.Logging Log Event Filtering](#microsoftextensionslogging-log-event-filtering)\n\n\u003ca id=\"supported-packages\"\u003e\u003c/a\u003e\n# Supported Packages\n\n\u003ca id=\"akkanet-core-packages\"\u003e\u003c/a\u003e\n## Akka.NET Core Packages\n\n* `Akka.Hosting` - the core `Akka.Hosting` package, needed for everything\n* [`Akka.Remote.Hosting`](src/Akka.Remote.Hosting) - enables Akka.Remote configuration. Documentation can be read [here](src/Akka.Remote.Hosting/README.md)\n* [`Akka.Cluster.Hosting`](src/Akka.Cluster.Hosting) - used for Akka.Cluster, Akka.Cluster.Sharding, and Akka.Cluster.Tools. Documentation can be read [here](src/Akka.Cluster.Hosting/README.md)\n* [`Akka.Persistence.Hosting`](src/Akka.Persistence.Hosting/README.md) - used for adding persistence functionality to perform local database-less testing. Documentation can be read [here](src/Akka.Persistence.Hosting/README.md)\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"akka-persistence-plugins\"\u003e\u003c/a\u003e\n## Akka Persistence Plugins\n\n* [`Akka.Persistence.SqlServer.Hosting`](https://github.com/akkadotnet/Akka.Persistence.SqlServer/tree/dev/src/Akka.Persistence.SqlServer.Hosting) - used for Akka.Persistence.SqlServer support. Documentation can be read [here](https://github.com/akkadotnet/Akka.Persistence.SqlServer/blob/dev/src/Akka.Persistence.SqlServer.Hosting/README.md)\n* [`Akka.Persistence.PostgreSql.Hosting`](https://github.com/akkadotnet/Akka.Persistence.PostgreSql/tree/dev/src/Akka.Persistence.PostgreSql.Hosting) - used for Akka.Persistence.PostgreSql support. Documentation can be read [here](https://github.com/akkadotnet/Akka.Persistence.PostgreSql/blob/dev/src/Akka.Persistence.PostgreSql.Hosting/README.md)\n* [`Akka.Persistence.Azure.Hosting`](https://github.com/petabridge/Akka.Persistence.Azure) - used for Akka.Persistence.Azure support. Documentation can be read [here](https://github.com/petabridge/Akka.Persistence.Azure/blob/master/README.md)\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"akkahealthcheck\"\u003e\u003c/a\u003e\n## [Akka.HealthCheck](https://github.com/petabridge/akkadotnet-healthcheck)\n\nEmbed health check functionality for environments such as Kubernetes, ASP.NET, AWS, Azure, Pivotal Cloud Foundry, and more. Documentation can be read [here](https://github.com/petabridge/akkadotnet-healthcheck/blob/dev/README.md)\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"akkamanagement-plugins\"\u003e\u003c/a\u003e\n## [Akka.Management Plugins](https://github.com/akkadotnet/Akka.Management)\n\nUseful tools for managing Akka.NET clusters running inside containerized or cloud based environment. `Akka.Hosting` is embedded in each of its packages.\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"akkamanagement-core-package\"\u003e\u003c/a\u003e\n### Akka.Management Core Package\n\n* [`Akka.Management`](https://github.com/akkadotnet/Akka.Management/tree/dev/src/management/Akka.Management) - core module of the management utilities which provides a central HTTP endpoint for Akka management extensions. Documentation can be read [here](https://github.com/akkadotnet/Akka.Management/tree/dev/src/management/Akka.Management#akka-management)\n* `Akka.Management.Cluster.Bootstrap` - used to bootstrap a cluster formation inside dynamic deployment environments. Documentation can be read [here](https://github.com/akkadotnet/Akka.Management/tree/dev/src/management/Akka.Management#akkamanagementclusterbootstrap)\n  \u003e **NOTE**\n  \u003e\n  \u003e As of version 1.0.0, cluster bootstrap came bundled inside the core `Akka.Management` NuGet package and are part of the default HTTP endpoint for `Akka.Management`. All `Akka.Management.Cluster.Bootstrap` NuGet package versions below 1.0.0 should now be considered deprecated.\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"akkadiscovery-plugins\"\u003e\u003c/a\u003e\n### Akka.Discovery Plugins\n\n* [`Akka.Discovery.AwsApi`](https://github.com/akkadotnet/Akka.Management/tree/dev/src/discovery/aws/Akka.Discovery.AwsApi) - provides dynamic node discovery service for AWS EC2 environment. Documentation can be read [here](https://github.com/akkadotnet/Akka.Management/blob/dev/src/discovery/aws/Akka.Discovery.AwsApi/README.md)\n* [`Akka.Discovery.Azure`](https://github.com/akkadotnet/Akka.Management/tree/dev/src/discovery/azure/Akka.Discovery.Azure) - provides a dynamic node discovery service for Azure PaaS ecosystem. Documentation can be read [here](https://github.com/akkadotnet/Akka.Management/blob/dev/src/discovery/azure/Akka.Discovery.Azure/README.md)\n* [`Akka.Discovery.KubernetesApi`](https://github.com/akkadotnet/Akka.Management/tree/dev/src/discovery/kubernetes/Akka.Discovery.KubernetesApi) - provides a dynamic node discovery service for Kubernetes clusters. Documentation can be read [here](https://github.com/akkadotnet/Akka.Management/blob/dev/src/discovery/kubernetes/Akka.Discovery.KubernetesApi/README.md)\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"akkacoordination-plugins\"\u003e\u003c/a\u003e\n### Akka.Coordination Plugins\n\n* [`Akka.Coordination.KubernetesApi`](https://github.com/akkadotnet/Akka.Management/tree/dev/src/coordination/kubernetes/Akka.Coordination.KubernetesApi) - provides a lease-based distributed lock mechanism backed by [Kubernetes CRD](https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/) for [Akka.NET Split Brain Resolver](https://getakka.net/articles/clustering/split-brain-resolver.html), [Akka.Cluster.Sharding](https://getakka.net/articles/clustering/cluster-sharding.html), and [Akka.Cluster.Singleton](https://getakka.net/articles/clustering/cluster-singleton.html). Documentation can be read [here](https://github.com/akkadotnet/Akka.Management/blob/dev/src/coordination/kubernetes/Akka.Coordination.KubernetesApi/README.md)\n* [`Akka.Coordination.Azure`](https://github.com/akkadotnet/Akka.Management/tree/dev/src/coordination/azure/Akka.Coordination.Azure) - provides a lease-based distributed lock mechanism backed by [Microsoft Azure Blob Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-overview) for [Akka.NET Split Brain Resolver](https://getakka.net/articles/clustering/split-brain-resolver.html), [Akka.Cluster.Sharding](https://getakka.net/articles/clustering/cluster-sharding.html), and [Akka.Cluster.Singleton](https://getakka.net/articles/clustering/cluster-singleton.html). Documentation can be read [here](https://github.com/akkadotnet/Akka.Management/blob/dev/src/coordination/azure/Akka.Coordination.Azure/README.md)\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"summary\"\u003e\u003c/a\u003e\n# Summary\n\nWe want to make Akka.NET something that can be instantiated more typically per the patterns often used with the Microsoft.Extensions.Hosting APIs that are common throughout .NET.\n\n```csharp\nusing Akka.Hosting;\nusing Akka.Actor;\nusing Akka.Actor.Dsl;\nusing Akka.Cluster.Hosting;\nusing Akka.Remote.Hosting;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nbuilder.Services.AddAkka(\"MyActorSystem\", configurationBuilder =\u003e\n{\n    configurationBuilder\n        .WithRemoting(\"localhost\", 8110)\n        .WithClustering(new ClusterOptions(){ Roles = new[]{ \"myRole\" },\n            SeedNodes = new[]{ Address.Parse(\"akka.tcp://MyActorSystem@localhost:8110\")}})\n        .WithActors((system, registry) =\u003e\n    {\n        var echo = system.ActorOf(act =\u003e\n        {\n            act.ReceiveAny((o, context) =\u003e\n            {\n                context.Sender.Tell($\"{context.Self} rcv {o}\");\n            });\n        }, \"echo\");\n        registry.TryRegister\u003cEcho\u003e(echo); // register for DI\n    });\n});\n\nvar app = builder.Build();\n\napp.MapGet(\"/\", async (context) =\u003e\n{\n    var echo = context.RequestServices.GetRequiredService\u003cActorRegistry\u003e().Get\u003cEcho\u003e();\n    var body = await echo.Ask\u003cstring\u003e(context.TraceIdentifier, context.RequestAborted).ConfigureAwait(false);\n    await context.Response.WriteAsync(body);\n});\n\napp.Run();\n```\n\nNo HOCON. Automatically runs all Akka.NET application lifecycle best practices behind the scene. Automatically binds the `ActorSystem` and the `ActorRegistry`, another new 1.5 feature, to the `IServiceCollection` so they can be safely consumed via both actors and non-Akka.NET parts of users' .NET applications.\n\nThis should be open to extension in other child plugins, such as `Akka.Persistence.SqlServer`:\n\n```csharp\nbuilder.Services.AddAkka(\"MyActorSystem\", configurationBuilder =\u003e\n{\n    configurationBuilder\n        .WithRemoting(\"localhost\", 8110)\n        .WithClustering(new ClusterOptions()\n        {\n            Roles = new[] { \"myRole\" },\n            SeedNodes = new[] { Address.Parse(\"akka.tcp://MyActorSystem@localhost:8110\") }\n        })\n        .WithSqlServerPersistence(builder.Configuration.GetConnectionString(\"sqlServerLocal\"))\n        .WithShardRegion\u003cUserActionsEntity\u003e(\"userActions\", s =\u003e UserActionsEntity.Props(s),\n            new UserMessageExtractor(),\n            new ShardOptions(){ StateStoreMode = StateStoreMode.DData, Role = \"myRole\"})\n        .WithActors((system, registry) =\u003e\n        {\n            var userActionsShard = registry.Get\u003cUserActionsEntity\u003e();\n            var indexer = system.ActorOf(Props.Create(() =\u003e new Indexer(userActionsShard)), \"index\");\n            registry.TryRegister\u003cIndex\u003e(indexer); // register for DI\n        });\n})\n```\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"dependency-injection-outside-and-inside-akkanet\"\u003e\u003c/a\u003e\n# Dependency Injection Outside and Inside Akka.NET\n\nOne of the other design goals of Akka.Hosting is to make the dependency injection experience with Akka.NET as seamless as any other .NET technology. We accomplish this through two new APIs:\n\n* The `ActorRegistry`, a DI container that is designed to be populated with `Type`s for keys and `IActorRef`s for values, just like the `IServiceCollection` does for ASP.NET services.\n* The `IRequiredActor\u003cTKey\u003e` - you can place this type the constructor of any dependency injected resource and it will automatically resolve a reference to the actor stored inside the `ActorRegistry` with `TKey`. This is how we inject actors into ASP.NET, SignalR, gRPC, and other Akka.NET actors!\n\n\u003e **N.B.** The `ActorRegistry` and the `ActorSystem` are automatically registered with the `IServiceCollection` / `IServiceProvider` associated with your application.\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"registering-actors-with-the-actorregistry\"\u003e\u003c/a\u003e\n## Registering Actors with the `ActorRegistry`\n\nAs part of Akka.Hosting, we need to provide a means of making it easy to pass around top-level `IActorRef`s via dependency injection both within the `ActorSystem` and outside of it.\n\nThe `ActorRegistry` will fulfill this role through a set of generic, typed methods that make storage and retrieval of long-lived `IActorRef`s easy and coherent:\n\n* Fetch ActorRegistry from ActorSystem manually\n```csharp\nvar registry = ActorRegistry.For(myActorSystem); \n```\n\n* Provided by the actor builder\n```csharp\nbuilder.Services.AddAkka(\"MyActorSystem\", configurationBuilder =\u003e\n{\n    configurationBuilder\n        .WithActors((system, actorRegistry) =\u003e\n        {\n            var actor = system.ActorOf(Props.Create(() =\u003e new MyActor));\n            actorRegistry.TryRegister\u003cMyActor\u003e(actor); // register actor for DI\n        });\n});\n```\n\n* Obtaining the `IActorRef` manually\n```csharp\nvar registry = ActorRegistry.For(myActorSystem); \nregistry.Get\u003cIndex\u003e(); // use in DI\n```\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"injecting-actors-with-irequiredactortkey\"\u003e\u003c/a\u003e\n## Injecting Actors with `IRequiredActor\u003cTKey\u003e`\n\nSuppose we have a class that depends on having a reference to a top-level actor, a router, a `ShardRegion`, or perhaps a `ClusterSingleton` (common types of actors that often interface with non-Akka.NET parts of a .NET application):\n\n```csharp\npublic sealed class MyConsumer\n{\n    private readonly IActorRef _actor;\n\n    public MyConsumer(IRequiredActor\u003cMyActorType\u003e actor)\n    {\n        _actor = actor.ActorRef;\n    }\n\n    public async Task\u003cstring\u003e Say(string word)\n    {\n        return await _actor.Ask\u003cstring\u003e(word, TimeSpan.FromSeconds(3));\n    }\n}\n```\n\nThe `IRequiredActor\u003cMyActorType\u003e` will cause the Microsoft.Extensions.DependencyInjection mechanism to resolve `MyActorType` from the `ActorRegistry` and inject it into the `IRequired\u003cActor\u003cMyActorType\u003e` instance passed into `MyConsumer`.\n\nThe `IRequiredActor\u003cTActor\u003e` exposes a single property:\n\n```csharp\npublic interface IRequiredActor\u003cTActor\u003e\n{\n    /// \u003csummary\u003e\n    /// The underlying actor resolved via \u003csee cref=\"ActorRegistry\"/\u003e using the given \u003csee cref=\"TActor\"/\u003e key.\n    /// \u003c/summary\u003e\n    IActorRef ActorRef { get; }\n}\n```\n\nBy default, you can automatically resolve any actors registered with the `ActorRegistry` without having to declare anything special on your `IServiceCollection`:\n\n```csharp\nusing var host = new HostBuilder()\n  .ConfigureServices(services =\u003e\n  {\n      services.AddAkka(\"MySys\", (builder, provider) =\u003e\n      {\n          builder.WithActors((system, registry) =\u003e\n          {\n              var actor = system.ActorOf(Props.Create(() =\u003e new MyActorType()), \"myactor\");\n              registry.Register\u003cMyActorType\u003e(actor);\n          });\n      });\n      services.AddScoped\u003cMyConsumer\u003e();\n  })\n  .Build();\n  await host.StartAsync();\n```\n\nAdding your actor and your type key into the `ActorRegistry` is sufficient - no additional DI registration is required to access the `IRequiredActor\u003cTActor\u003e` for that type.\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"resolving-irequiredactortkey-within-akkanet\"\u003e\u003c/a\u003e\n## Resolving `IRequiredActor\u003cTKey\u003e` within Akka.NET\n\nAkka.NET does not use dependency injection to start actors by default primarily because actor lifetime is unbounded by default - this means reasoning about the scope of injected dependencies isn't trivial. ASP.NET, by contrast, is trivial: all HTTP requests are request-scoped and all web socket connections are connection-scoped - these are objects have _bounded_ and typically short lifetimes.\n\nTherefore, users have to explicitly signal when they want to use Microsoft.Extensions.DependencyInjection via [the `IDependencyResolver` interface in Akka.DependencyInjection](https://getakka.net/articles/actors/dependency-injection.html) - which is easy to do in most of the Akka.Hosting APIs for starting actors:\n\n```csharp\nvar builder = WebApplication.CreateBuilder(args);\n\nbuilder.Services.AddScoped\u003cIReplyGenerator, DefaultReplyGenerator\u003e();\nbuilder.Services.AddAkka(\"MyActorSystem\", configurationBuilder =\u003e\n{\n    configurationBuilder\n        .WithRemoting(hostname: \"localhost\", port: 8110)\n        .WithClustering(new ClusterOptions{SeedNodes = new []{ \"akka.tcp://MyActorSystem@localhost:8110\", }})\n        .WithShardRegion\u003cEcho\u003e(\n            typeName: \"myRegion\",\n            entityPropsFactory: (_, _, resolver) =\u003e\n            {\n                // uses DI to inject `IReplyGenerator` into EchoActor\n                return s =\u003e resolver.Props\u003cEchoActor\u003e(s);\n            },\n            extractEntityId: ExtractEntityId,\n            extractShardId: ExtractShardId,\n            shardOptions: new ShardOptions());\n});\n```\n\nThe `dependencyResolver.Props\u003cMySingletonDiActor\u003e()` call will leverage the `ActorSystem`'s built-in `IDependencyResolver` to instantiate the `MySingletonDiActor` and inject it with all of the necessary dependencies, including `IRequiredActor\u003cTKey\u003e`.\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"microsoftextensionsconfiguration-integration\"\u003e\u003c/a\u003e\n# Microsoft.Extensions.Configuration Integration\n\n\u003ca id=\"iconfiguration-to-hocon-adapter\"\u003e\u003c/a\u003e\n## IConfiguration To HOCON Adapter\n\nThe `AddHocon` extension method can convert `Microsoft.Extensions.Configuration` `IConfiguration` into HOCON `Config` instance and adds it to the ActorSystem being configured.\n* Unlike `IConfiguration`, all HOCON key names are **case sensitive**.\n* **Unless enclosed inside double quotes**, all \".\" (period) in the `IConfiguration` key will be treated as a HOCON object key separator\n* `IConfiguration` **does not support object composition**, if you declare the same key multiple times inside multiple configuration providers (JSON/environment variables/etc), **only the last one declared will take effect**.\n* For environment variable configuration provider:\n   * \"__\" (double underline) will be converted to \".\" (period).\n   * \"_\" (single underline) will be converted to \"-\" (dash).\n   * If all keys are composed of integer parseable keys, the whole object is treated as an array\n\n__Example:__\n\n`appsettings.json`:\n\n```json\n{\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Information\",\n      \"Microsoft.AspNetCore\": \"Warning\"\n    }\n  },\n  \"AllowedHosts\": \"*\",\n  \"akka\": {\n    \"cluster\": {\n      \"roles\": [ \"front-end\", \"back-end\" ],\n      \"min-nr-of-members\": 3,\n      \"log-info\": true\n    }\n  }    \n}\n```\n\nEnvironment variables:\n\n```powershell\nAKKA__ACTOR__TELEMETRY__ENABLE=true\nAKKA__CLUSTER__SEED_NODES__0=akka.tcp//mySystem@localhost:4055\nAKKA__CLUSTER__SEED_NODES__1=akka.tcp//mySystem@localhost:4056\nAKKA__CLUSTER__SEED_NODE_TIMEOUT=00:00:05\n```\n\nNote the integer parseable key inside the seed-nodes configuration, seed-nodes will be parsed as an array. These environment variables will be parsed as HOCON settings:\n\n```hocon\nakka {\n  actor {\n    telemetry.enabled: on\n  }\n  cluster {\n    seed-nodes: [ \n      \"akka.tcp//mySystem@localhost:4055\",\n      \"akka.tcp//mySystem@localhost:4056\" \n    ]\n    seed-node-timeout: 5s\n  }\n}\n```\n\nExample code:\n\n```csharp\n/*\nBoth appsettings.json and environment variables are combined\ninto HOCON configuration:\n\nakka {\n  actor.telemetry.enabled: on\n  cluster {\n    roles: [ \"front-end\", \"back-end\" ]\n    seed-nodes: [ \n      \"akka.tcp//mySystem@localhost:4055\",\n      \"akka.tcp//mySystem@localhost:4056\" \n    ]\n    min-nr-of-members: 3\n    seed-node-timeout: 5s\n    log-info: true\n  }\n}\n*/\nvar host = new HostBuilder()\n    .ConfigureHostConfiguration(builder =\u003e\n    {\n        // Setup IConfiguration to load from appsettings.json and\n        // environment variables\n        builder\n            .AddJsonFile(\"appsettings.json\")\n            .AddEnvironmentVariables();\n    })\n    .ConfigureServices((context, services) =\u003e\n    {\n        services.AddAkka(\"mySystem\", (builder, provider) =\u003e\n            {\n                // convert IConfiguration to HOCON\n                var akkaConfig = context.Configuration.GetSection(\"akka\");\n                builder.AddHocon(akkaConfig, HoconAddMode.Prepend); \n            });\n    });\n```\n\n### Special Characters And Case Sensitivity\n\nThis advanced usage of the `IConfiguration` adapter is solely used for edge cases where HOCON key capitalization needs to be preserved, such as declaring serialization binding. Note that when you're using this feature, none of the keys are normalized, you will have to write all of your keys in a HOCON compatible way.\n\n`appsettings.json`:\n\n```json\n{\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Information\",\n      \"Microsoft.AspNetCore\": \"Warning\"\n    }\n  },\n  \"AllowedHosts\": \"*\",\n  \"akka\": {\n    \"\\\"Key.With.Dots\\\"\": \"Key Value\",\n    \"cluster\": {\n      \"roles\": [ \"front-end\", \"back-end\" ],\n      \"min-nr-of-members\": 3,\n      \"log-info\": true\n    }\n  }    \n}\n```\n\nNote that \"Key.With.Dots\" needs to be inside escaped double quotes, this is a HOCON requirement that preserves the \".\" (period) inside HOCON property names.\n\nEnvironment variables:\n\n```powershell\nPS C:/\u003e [Environment]::SetEnvironmentVariable('akka__actor__telemetry__enabled', 'true')\nPS C:/\u003e [Environment]::SetEnvironmentVariable('akka__actor__serialization_bindings__\"System.Object\"', 'hyperion')\nPS C:/\u003e [Environment]::SetEnvironmentVariable('akka__cluster__seed_nodes__0', 'akka.tcp//mySystem@localhost:4055')\nPS C:/\u003e [Environment]::SetEnvironmentVariable('akka__cluster__seed_nodes__1', 'akka.tcp//mySystem@localhost:4056')\nPS C:/\u003e [Environment]::SetEnvironmentVariable('akka__cluster__seed_node_timeout', '00:00:05')\n```\n\nNote that:\n1. All of the environment variable names are in lower case, except \"System.Object\" where it needs to preserve name capitalization.\n2. To set serialization binding via environment variable, you have to use \".\" (period) instead of \"__\" (double underscore), this might be problematic for some shell scripts and there is no way of getting around this.\n\nExample code:\n\n```csharp\n/*\nBoth appsettings.json and environment variables are combined\ninto HOCON configuration:\n\nakka {\n  \"Key.With.Dots\": Key Value\n  actor {\n    telemetry.enabled: on\n    serialization-bindings {\n      \"System.Object\" = hyperion\n    }\n  }\n  cluster {\n    roles: [ \"front-end\", \"back-end\" ]\n    seed-nodes: [ \n      \"akka.tcp//mySystem@localhost:4055\",\n      \"akka.tcp//mySystem@localhost:4056\" \n    ]\n    min-nr-of-members: 3\n    seed-node-timeout: 5s\n    log-info: true\n  }\n}\n*/\nvar host = new HostBuilder()\n    .ConfigureHostConfiguration(builder =\u003e\n    {\n        // Setup IConfiguration to load from appsettings.json and\n        // environment variables\n        builder\n            .AddJsonFile(\"appsettings.json\")\n            .AddEnvironmentVariables();\n    })\n    .ConfigureServices((context, services) =\u003e\n    {\n        services.AddAkka(\"mySystem\", (builder, provider) =\u003e\n            {\n                // convert IConfiguration to HOCON\n                var akkaConfig = context.Configuration.GetSection(\"akka\");\n                // Note the last method argument is set to false\n                builder.AddHocon(akkaConfig, HoconAddMode.Prepend, false); \n            });\n    });\n```\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"microsoftextensionslogging-integration\"\u003e\u003c/a\u003e\n# Microsoft.Extensions.Logging Integration\n\n\u003ca id=\"logger-configuration-support\"\u003e\u003c/a\u003e\n## Logger Configuration Support\n\nYou can use `AkkaConfigurationBuilder` extension method called `ConfigureLoggers(Action\u003cLoggerConfigBuilder\u003e)` to configure how Akka.NET logger behave.\n\nExample:\n```csharp\nbuilder.Services.AddAkka(\"MyActorSystem\", configurationBuilder =\u003e\n{\n    configurationBuilder\n        .ConfigureLoggers(setup =\u003e\n        {\n            // Example: This sets the minimum log level\n            setup.LogLevel = LogLevel.DebugLevel;\n            \n            // Example: Clear all loggers\n            setup.ClearLoggers();\n            \n            // Example: Add the default logger\n            // NOTE: You can also use setup.AddLogger\u003cDefaultLogger\u003e();\n            setup.AddDefaultLogger();\n            \n            // Example: Add the ILoggerFactory logger\n            // NOTE:\n            //   - You can also use setup.AddLogger\u003cLoggerFactoryLogger\u003e();\n            //   - To use a specific ILoggerFactory instance, you can use setup.AddLoggerFactory(myILoggerFactory);\n            setup.AddLoggerFactory();\n            \n            // Example: Adding a serilog logger\n            setup.AddLogger\u003cSerilogLogger\u003e();\n        })\n        .WithActors((system, registry) =\u003e\n        {\n            var echo = system.ActorOf(act =\u003e\n            {\n                act.ReceiveAny((o, context) =\u003e\n                {\n                    Logging.GetLogger(context.System, \"echo\").Info($\"Actor received {o}\");\n                    context.Sender.Tell($\"{context.Self} rcv {o}\");\n                });\n            }, \"echo\");\n            registry.TryRegister\u003cEcho\u003e(echo); // register for DI\n        });\n});\n```\n\nA complete code sample can be viewed [here](https://github.com/akkadotnet/Akka.Hosting/tree/dev/src/Examples/Akka.Hosting.LoggingDemo).\n\nExposed properties are:\n- `LogLevel`: Configure the Akka.NET minimum log level filter, defaults to `InfoLevel`\n- `LogConfigOnStart`: When set to true, Akka.NET will log the complete HOCON settings it is using at start up, this can then be used for debugging purposes.\n\nCurrently supported logger methods:\n- `ClearLoggers()`: Clear all registered logger types.\n- `AddLogger\u003cTLogger\u003e()`: Add a logger type by providing its class type.\n- `AddDefaultLogger()`: Add the default Akka.NET console logger.\n- `AddLoggerFactory()`: Add the new `ILoggerFactory` logger.\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"microsoftextensionsloggingiloggerfactory-logging-support\"\u003e\u003c/a\u003e\n## Microsoft.Extensions.Logging.ILoggerFactory Logging Support\n\nYou can now use `ILoggerFactory` from Microsoft.Extensions.Logging as one of the sinks for Akka.NET logger. This logger will use the `ILoggerFactory` service set up inside the dependency injection `ServiceProvider` as its sink.\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"serilog-support\"\u003e\u003c/a\u003e\n## Serilog Message Formatting Support\n\nIf you're interested in using [Akka.Logger.Serilog](https://github.com/akkadotnet/Akka.Logger.Serilog), you can set Akka.NET's default logger and log message formatter to allow for Serilog's semantic logging to be enabled by default:\n\n```csharp\nbuilder.Services.AddAkka(\"MyActorSystem\", configurationBuilder =\u003e\n{\n    configurationBuilder\n        .ConfigureLoggers(setup =\u003e\n        {\n            // Example: This sets the minimum log level\n            setup.LogLevel = LogLevel.DebugLevel;\n            \n            // Example: Clear all loggers\n            setup.ClearLoggers();\n            \n            // Add Serilog\n            setup.AddLogger\u003cSerilogLogger\u003e();\n            \n            // use the default SerilogFormatter everywhere\n            setup.WithDefaultLogMessageFormatter\u003cSerilogLogMessageFormatter\u003e();\n        })\n        .WithActors((system, registry) =\u003e\n        {\n            var echo = system.ActorOf(act =\u003e\n            {\n                act.ReceiveAny((o, context) =\u003e\n                {\n                    Logging.GetLogger(context.System, \"echo\").Info($\"Actor received {o}\");\n                    context.Sender.Tell($\"{context.Self} rcv {o}\");\n                });\n            }, \"echo\");\n            registry.TryRegister\u003cEcho\u003e(echo); // register for DI\n        });\n});\n```\n\nThis will eliminate the need to have to do `Context.GetLogger\u003cSerilogLoggingAdapter\u003e()` everywhere you want to use it.\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"microsoftextensionslogging-log-event-filtering\"\u003e\u003c/a\u003e\n## Microsoft.Extensions.Logging Log Event Filtering\n\nThere will be two log event filters acting on the final log input, the Akka.NET `akka.loglevel` setting and the `Microsoft.Extensions.Logging` settings, make sure that both are set correctly or some log messages will be missing.\n\nTo set up the `Microsoft.Extensions.Logging` log filtering, you will need to edit the `appsettings.json` file. Note that we also set the `Akka` namespace to be filtered at debug level in the example below.\n\n```json\n{\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Information\",\n      \"Microsoft\": \"Warning\",\n      \"Microsoft.Hosting.Lifetime\": \"Information\",\n      \"Akka\": \"Debug\"\n    }\n  }\n}\n```\n\n[Back to top](#akkahosting)\n\n\u003ca id=\"filtering-logs\"\u003e\u003c/a\u003e\n## Filtering Logs In Akka.NET\n\nIn Akka.NET 1.5.21, we introduced [log filtering for log messages based on the LogSource or the content of a log message](https://getakka.net/articles/utilities/logging.html#filtering-log-messages). Depending on your coding style, you can use this feature in Akka.Hosting in several ways.\n\n1. Using The `LoggerConfigBuilder.WithLogFilter()` method.\n\n   The `LoggerConfigBuilder.WithLogFilter()` method lets you set up the `LogFilterBuilder`\n\n   ```csharp\n   builder.Services.AddAkka(\"MyActorSystem\", configurationBuilder =\u003e\n   {\n       configurationBuilder\n           .ConfigureLoggers(loggerConfigBuilder =\u003e\n           {\n               loggerConfigBuilder.WithLogFilter(filterBuilder =\u003e\n               {\n                   filterBuilder.ExcludeMessageContaining(\"Test\");\n               });\n           });\n   });\n   ```\n\n2. Setting the `loggerConfigBuilder.LogFilterBuilder` property directly.\n\n   ```csharp\n   builder.Services.AddAkka(\"MyActorSystem\", configurationBuilder =\u003e\n   {\n       configurationBuilder\n           .ConfigureLoggers(loggerConfigBuilder =\u003e\n           {\n               loggerConfigBuilder.LogFilterBuilder = new LogFilterBuilder();\n               loggerConfigBuilder.LogFilterBuilder.ExcludeMessageContaining(\"Test\");\n           });\n   });\n   ```\n\n[Back to top](#akkahosting)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakkadotnet%2Fakka.hosting","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fakkadotnet%2Fakka.hosting","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakkadotnet%2Fakka.hosting/lists"}