First, open the robot permission

First find the company’s administrative department to open the enterprise wechat robot rights. After opening relevant permissions, you will find that relevant robots can be added to the company’s wechat group at this time, as shown in the picture below:

Create a robot, log monitor robot, for Sentry error reporting, as shown in the figure below.

Go to the Sentry server, find the project, and click the Settings button.

Copy the Webhook of the enterprise wechat robot just generated into the corresponding project of Sentry server, click save, and you are done, isn’t it very exciting!!

Click the button of the test plug-in, and find that the wechat robot of the enterprise has not received the relevant log reminder. Hey, what’s going on here? Is the posture of the copy wrong?

The main reason for this problem is that the format of data packets sent by Sentry calling Webhook is inconsistent with that required by enterprise wechat robot, as shown below:

Data message format required by enterprise wechat robot:

{
    "msgtype": "text"."text": {
        "content": "Weather in Guangzhou today: 29 degrees, mostly cloudy, chance of rain: 60%"."mentioned_list": ["wangqing"."@all"]."mentioned_mobile_list": ["13800001111"."@all"]}}Copy the code

Format of data packets sent by Sentry:

{
  id: '7',
  project: 'ii-admin-pro',
  project_name: 'ii-admin-pro',
  project_slug: 'ii-admin-pro',
  logger: null,
  level: 'error',
  culprit: 'raven.scripts.runner in main',
  message: 'This is an example Python exception',
  url: 'http://sentry.xxxxxxx.com/organizations/sentry/issues/7/?referrer=webhooks_plugin',
  triggering_rules: [],
  event: {
    event_id: 'f602ac321ee04bc28a20c9f4d446ef48',
    level: 'error',
    version: '5',
    type: 'default',
    logentry: {
      formatted: 'This is an example Python exception',
      message: null,
      params: null
    },
    logger: '',
    modules: { 'my.package': '1.0. 0' },
    platform: 'python',
    timestamp: 1622734089.769465,
    received: 1622734089.7702,
    environment: 'prod',
    user: {
      id: '1',
      email: '[email protected]',
      ip_address: '127.0. 01.',
      username: 'sentry',
      name: 'Sentry',
      geo: [Object]
    },
    request: {
      url: 'http://example.com/foo',
      method: 'GET',
      data: [Object],
      query_string: [Array],
      cookies: [Array],
      headers: [Array],
      env: [Object],
      inferred_content_type: 'application/json',
      fragment: null},... }}Copy the code

To solve the problem of inconsistent data message formats, it is necessary to build a Node service at this time to make downconversion of Sentry data messages and send them according to the data message format of the enterprise wechat robot.

2. Build the Node service

The author quickly built a Node service based on egg.js, and the routing configuration is as follows:

In the app/controller/robot sentry. Create SentryController js file, used to be responsible for the data message transformation, as shown in the code:

'use strict';

const Controller = require('egg').Controller;
const request = require('.. /.. /utils/request');
const { SENTRY_HOOKS } = require('.. /.. /utils/const');
const { fmtDateTime, genProjectOwners } = require('.. /.. /utils/utils');

class SentryController extends Controller {
  /** * Receive Webhook from Sentry */
  async recvSentryWebhook() {
    const {
      params,
      request: { body },
    } = this.ctx;

    const ROBOT_DATA = {
      msgtype: 'markdown'.markdown: {
        content: `!!!!!! Front end item <font color= "warning ">${body.project_name}<font color= "info ">${body.culprit}<font color= "info ">${fmtDateTime()}</font> > Error level: <font color= "info ">${body.level}</font> >${body.url}) \n Please note that:${genProjectOwners(SENTRY_HOOKS[params.name].owners)}`,}};const result = await request({
      url: SENTRY_HOOKS[params.name].sentry_hook,
      method: 'POST'.headers: {
        'content-type': 'application/json',},data: JSON.stringify(ROBOT_DATA),
    });

    this.ctx.body = {
      code: '0'.data: result,
      msg: 'Remind success'}; }}module.exports = SentryController;
Copy the code

Utils/utils. Js file

/** * Formats the current time */
const fmtDateTime = () = > {
  let date = new Date(a);let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let hour = date.getHours();
  let min = date.getMinutes();

  month = month < 10 ? ` 0${month}` : month;
  hour = hour < 10 ? ` 0${hour}` : hour;
  min = min < 10 ? ` 0${min}` : min;

  return `${year}-${month}-${date.getDate()} ${hour}:${min}`;
};

/** * Generate project leader */
const genProjectOwners = (owners) = > {
  return owners.map((item) = > ` < @${item}> `).join(' ');
};

module.exports = {
  fmtDateTime,
  genProjectOwners,
};

Copy the code

utils/const.js

It is mainly used to store configuration constants. If there is a new project, you only need to add the new project configuration to the constant file.

Among them:

  • The owners are storing the enterprise wechat userid. Userid is the prefix of the enterprise email address, for example, [email protected]. Userid is xiaoli.

Yaml Production pM2 is used to manage the online Node service. Run pM2 to deploy server. yaml production, synchronize the local code online, and restart the Node service. It is not the focus of this article and will be skipped here).

Copy the online interface address to the corresponding Webhooks address of Sentry server. After saving, click the test plug-in button to test whether the log monitoring robot is effective, as shown below:

At this time, the enterprise wechat group successfully received the log reminder sent by Sentry, as shown below:

At this point, you’re done!

Note: If your Sentry service is deployed online and not on a local LAN during development, you will not receive the log alarms sent by Sentry during Node service debugging. In this case, you need to perform Intranet penetration or connect your Node service to the online. ! I have been stuck on this issue for a day or two.

Other references:

  • Set up the Sentry service
  • Access the Sentry service