简体   繁体   中英

Distinguish different environments of logs in Azure Static Web Apps (SWA) in Application Insights

Azure Static Web Apps have the possibility to create "Staging environments" automatically for new PullRequests done via GitHub .

This works quite well, however with the problem that whenmonitoring gets enabled via Azure Application Insights, all of the traces and exceptions of the "productive" SWA application and all of the currently deployed staging environments are appended in the same log tables (eg in traces ).

Is it possible to somehow select the environment as a column or create a KQL query which filters eg only for "production"?

I am aware that I also could configure a separate Application Insights instance for each created staging environment - but then I would have to adjust the APPINSIGHTS_INSTRUMENTATIONKEY application setting differently for each newly created environment (which by default just copies the settings from "production" when a new PR is created).

I ended up solving this in the following way:

  1. Define a placeholde in the source files where the "environment" should be injected: const envName = "__ENVIRONMENT_NAME__";
  2. Enhanced the GitHub action using Azure/static-web-apps-deploy by some steps before build+deployment to determine the branch name and replacing the placeholder in all TypeScript *.ts files via find + -exec sed with the branch name:
      - name: Get branch name (merge)
        if: github.event_name != 'pull_request'
        shell: bash
        run: echo "BRANCH_NAME=$(echo ${GITHUB_REF#refs/heads/} | tr / -)" >> $GITHUB_ENV
      - name: Get branch name (pull request)
        if: github.event_name == 'pull_request'
        shell: bash
        run: echo "BRANCH_NAME=$(echo ${GITHUB_HEAD_REF} | tr / -)" >> $GITHUB_ENV
      - name: Inject environment name in api function files
        run: |
          find ./api -name "*.ts" -not -path "./api/node_modules/*" -exec sed -i "s@__ENVIRONMENT_NAME__@${{ env.BRANCH_NAME }}@g" {} +
  1. Creating a custom logger, wrapping the Azure function Context.Logger :
import { Logger } from "@azure/functions"

const envName = "__ENVIRONMENT_NAME__"; // injected via GH actions build

export class MyLogger {
    private azLogger: Logger;

    constructor(realLogger: Logger) {
        this.azLogger = realLogger;
    }

    public error(...args: any[]): void {
        this.azLogger.error(`[${envName}] ` + args[0], args.shift());
    }

    public warn(...args: any[]): void {
        this.azLogger.warn(`[${envName}] ` + args[0], args.shift());
    }

    public info(...args: any[]): void {
        this.azLogger.info(`[${envName}] ` + args[0], args.shift());
    }

    public verbose(...args: any[]): void {
        this.azLogger.verbose(`[${envName}] ` + args[0], args.shift());
    }
}
  1. Instantiate the MyLogger in the AzureFunction http function and afterwards always use the custom logger for logging:
const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
  const logger = new MyLogger(context.log);
  logger.info('HTTP trigger function processed a request.');
  ...
}
  1. Enhance the Azure Application Insights KQL query to extract the "environment" as a separate column:
traces
| order by timestamp desc 
| parse message with '[' environment ']' msg
| extend TheMsg=iif(msg != '', msg, message)
| project timestamp, ENV=environment, OP=operation_Name, MSG=TheMsg

So without the need to use the "applicationinsights" npm dependency and doing complicated configuration, the environment name is available as separate column in the logs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM