You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为AKS上的.NET Core控制台容器配置监控?

.NET Core Worker Service on AKS: Fixing Missing Logs & Correct Monitoring Configuration

Let’s break this down step by step—first we’ll tackle the missing console logs issue, then refine your Application Insights/Log Analytics setup to work reliably on AKS.

1. Fixing Missing Console Logs in AKS

Your code already includes loggingBuilder.AddConsole(...), which is correct for sending logs to stdout/stderr (the default way Kubernetes captures container logs). If you’re not seeing logs via kubectl logs <pod-name>, check these common issues:

a. Verify Log Level Configuration

Double-check that your code is emitting logs at or above the level set in your config:

  • Your appsettings.json sets Default: Information, so ensure you’re using _logger.LogInformation(...) (or higher) in your RunsQueueProcessor code—LogDebug won’t show up here.
  • If you’ve set environment variables in your AKS deployment that override logging settings (via AddEnvironmentVariables() in your code), confirm they’re not restricting log levels. For example, a Logging__Default=Warning env var would suppress Information-level logs.

b. Check Container Startup Logs

Run kubectl logs <pod-name> right after starting the pod to see if the app is initializing properly. If you see no output at all, the app might be crashing before emitting logs—use kubectl describe pod <pod-name> to check for startup errors or crash loop backoffs.

c. Ensure Logs Are Sent to Stdout

.NET Core worker services should send console logs to stdout by default, but you can explicitly confirm this by updating your logging config:

.ConfigureLogging((hostBuilderContext, loggingBuilder) => {
    loggingBuilder.ClearProviders(); // Remove other providers if needed
    loggingBuilder.AddConsole(options => {
        options.TimestampFormat = "[HH:mm:ss]";
        options.LogToStandardErrorThreshold = LogLevel.None; // Send all logs to stdout
    });
})

2. Correct Application Insights Monitoring Setup

Your current code adds the necessary packages (AddApplicationInsightsTelemetryWorkerService and AddApplicationInsightsKubernetesEnricher), but let’s optimize the configuration for AKS:

a. Securely Pass the Instrumentation Key

Hardcoding the Instrumentation Key in appsettings.json is bad practice. Instead, use an AKS Secret to inject it as an environment variable:

  1. Create a secret in your AKS namespace:
    kubectl create secret generic appinsights-secret --from-literal=instrumentationkey=<your-instrumentation-key>
    
  2. Update your deployment YAML to inject the secret as an env var:
    spec:
      containers:
      - name: <container>
        image: <acr>.azurecr.io/<container>:{tag}
        env:
        - name: APPINSIGHTS_INSTRUMENTATIONKEY
          valueFrom:
            secretKeyRef:
              name: appinsights-secret
              key: instrumentationkey
    
    .NET Core’s Application Insights SDK will automatically pick up this env var, so you can remove the InstrumentationKey line from appsettings.json if you want.

b. Enable Kubernetes Metadata Enrichment (RBAC Permissions)

The AddApplicationInsightsKubernetesEnricher needs permissions to query the AKS API for pod/node metadata. If your AKS cluster uses RBAC (which is default), create these permissions:

  1. Create a ClusterRole with access to Kubernetes resources:
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRole
    metadata:
      name: ai-kubernetes-enricher
    rules:
    - apiGroups: [""]
      resources: ["pods", "nodes", "namespaces"]
      verbs: ["get", "list", "watch"]
    
  2. Bind the role to your worker’s service account (assuming you’re using the default service account in the default namespace):
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
      name: ai-kubernetes-enricher-binding
    subjects:
    - kind: ServiceAccount
      name: default
      namespace: default
    roleRef:
      kind: ClusterRole
      name: ai-kubernetes-enricher
      apiGroup: rbac.authorization.k8s.io
    
    Apply these files with kubectl apply -f <filename>.yaml.

c. Verify Telemetry in Application Insights

After making these changes, check your Application Insights resource:

  • Go to Logs (Analytics) and run the query: traces | limit 100 to see your application logs.
  • Check Metrics to see if worker service telemetry (like request duration, exceptions) is being captured.

3. Optional: Integrate with Log Analytics

If you want to centralize all container logs (including stdout/stderr) alongside Application Insights telemetry, enable Azure Monitor for Containers for your AKS cluster:

  • This will send all container logs to Log Analytics’ ContainerLog table, so you can query both application logs and Kubernetes system logs in one place.
  • You can enable this via the Azure Portal (go to your AKS cluster → Monitoring → Insights → Enable) or using Azure CLI.

Final Check List

  • Confirm kubectl logs <pod-name> shows your application logs.
  • Use AKS Secrets instead of hardcoding sensitive keys.
  • Grant RBAC permissions for Application Insights Kubernetes enrichment.
  • Validate telemetry in both Application Insights and Log Analytics (if enabled).

内容的提问来源于stack exchange,提问作者Carlos Garcia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:33:23