1 | import {FEFLOW_ROOT, LOG_FILE} from "../../shared/constant";
|
2 | import osenv from "osenv";
|
3 | const fs = require('fs');
|
4 | const axios = require('axios');
|
5 | const path = require('path');
|
6 | const os = require('os');
|
7 | const LOGGER_LOG_PATH = path.join(osenv.home(), FEFLOW_ROOT, LOG_FILE);
|
8 | const KEYS_FILE = path.join(__dirname, '../../../.keys');
|
9 | const USER_NAME = os.hostname().split("-")[0];
|
10 | const NOW_TIME = new Date().getTime();
|
11 | const pkg = require('../../../package.json');
|
12 | const PLUGE_NAME = 'feflow-' + pkg.name.split('/').pop();
|
13 | const { hasTimer } = process.env;
|
14 | let KYE_FILE = {};
|
15 | interface IObject {
|
16 | [key: string]: string;
|
17 | }
|
18 | (async ()=>{
|
19 | try{
|
20 | KYE_FILE = JSON.parse(fs.readFileSync(KEYS_FILE, 'utf-8'));
|
21 | }catch(err){}
|
22 | if(!KYE_FILE['time'] || NOW_TIME - KYE_FILE['time'] > 5184e6){
|
23 | let {data:{result}} = await axios.get(`http://log.feflowjs.com/api/v1/summary/getskey?rtx=${USER_NAME}`);
|
24 | KYE_FILE = {
|
25 | time: NOW_TIME,
|
26 | skey: result.skey
|
27 | }
|
28 | fs.writeFileSync(KEYS_FILE,JSON.stringify(KYE_FILE),'utf-8')
|
29 | }
|
30 | })();
|
31 |
|
32 | const levelNames: IObject = {
|
33 | 10: 'Trace',
|
34 | 20: 'Debug',
|
35 | 30: 'Info',
|
36 | 40: 'Warn',
|
37 | 50: 'Error',
|
38 | 60: 'Fatal'
|
39 | };
|
40 |
|
41 | export let timer: NodeJS.Timeout | null = null;
|
42 |
|
43 | async function send(logObj: any, readData: [any]) {
|
44 | const loggerList = readData.filter((data: string) => data).map((data: string) => {
|
45 | const logger = JSON.parse(data);
|
46 | const level = logger.level;
|
47 | const loggerName = logger.name || (logObj.name && logObj.name.split('/').pop()) || PLUGE_NAME;
|
48 | return {
|
49 | level: level,
|
50 | msg: `[Feflow ${levelNames[level]}][${loggerName}]${logger.msg}`,
|
51 | date: new Date().getTime(),
|
52 | name: loggerName
|
53 | };
|
54 | });
|
55 |
|
56 | fs.writeFile(LOGGER_LOG_PATH, '', 'utf8', () => {
|
57 |
|
58 | });
|
59 | const response = await axios.post('http://log.feflowjs.com/api/v1/log/save', {
|
60 | plugin: loggerList[0]['name'],
|
61 | data: JSON.stringify(loggerList)
|
62 | },{
|
63 | headers: {
|
64 | skey: KYE_FILE['skey'],
|
65 | rtx: USER_NAME
|
66 | }
|
67 | });
|
68 | if(response.status===204){
|
69 | console.log('send success');
|
70 | }
|
71 | }
|
72 | async function report(logObj?: any) {
|
73 | let readData = fs.readFileSync(LOGGER_LOG_PATH, 'utf-8');
|
74 | if (readData) {
|
75 | readData = readData.split('\n');
|
76 |
|
77 | if (readData.length < 20) {
|
78 |
|
79 | if (!hasTimer) {
|
80 | timer = setTimeout(async () => {
|
81 | await send(logObj, readData);
|
82 | timer && clearTimeout(timer);
|
83 | timer = null;
|
84 | }, 5000);
|
85 | }
|
86 | return;
|
87 | }
|
88 | timer && clearTimeout(timer);
|
89 | timer = null;
|
90 | await send(logObj, readData);
|
91 | }
|
92 | }
|
93 | report();
|