Replaced all console.log with new logger function

This commit is contained in:
Douglas Barone 2020-12-18 12:07:33 -04:00
parent 4d836c2260
commit 6332f297cb
8 changed files with 163 additions and 49 deletions

View File

@ -8,6 +8,7 @@ import config from '../lib/activeDirectory/config'
import jwt from 'jsonwebtoken' import jwt from 'jsonwebtoken'
import { pubsub, AUTH_UPDATED } from '../pubsub' import { pubsub, AUTH_UPDATED } from '../pubsub'
import { logError, logInfo, logSuccess, logWarning } from '../lib/logger'
class User { class User {
constructor(username) { constructor(username) {
@ -139,7 +140,11 @@ class User {
client.on('error', err => { client.on('error', err => {
client.unbind(() => { client.unbind(() => {
console.log('Client unbinded due error.') logError({
message: 'Client unbinded due error.',
data: err,
tags: ['ldap']
})
}) })
reject(new Error(err.message)) reject(new Error(err.message))
}) })
@ -186,13 +191,21 @@ class User {
(err, result) => { (err, result) => {
if (err) { if (err) {
client.unbind(() => { client.unbind(() => {
console.log('Client unbinded due error.') logError({
message: 'Client unbinded. Error updating password',
data: err,
tags: ['ldap']
})
}) })
reject(new Error(err.message)) reject(new Error(err.message))
} else { } else {
User.upsertUser(this.username) User.upsertUser(this.username)
client.unbind(() => { client.unbind(() => {
console.log('Client unbinded') logSuccess({
message: `Client unbinded. Password updated for user ${this.username}`,
data: result,
tags: ['ldap']
})
}) })
resolve(User.login(this.username, newPassword)) resolve(User.login(this.username, newPassword))
} }
@ -315,21 +328,30 @@ class User {
static async importAllUsers() { static async importAllUsers() {
if (this.working) { if (this.working) {
console.log('Já há uma importação em andamento') logWarning({
tags: ['user'],
message: 'User import aborted: already working'
})
return 0 return 0
} }
this.working = true this.working = true
try { try {
console.log('Obtendo usuários do AD...') logInfo({
tags: ['user'],
message: 'Importing users from Active Directory'
})
const allAdUsers = await ad.findUsers({ const allAdUsers = await ad.findUsers({
paged: true, paged: true,
filter: '(!(userAccountControl:1.2.840.113556.1.4.803:=2))' // Only active users filter: '(!(userAccountControl:1.2.840.113556.1.4.803:=2))' // Only active users
}) })
console.log('Importando usuários...') logInfo({
tags: ['user'],
message: 'Importing users to database'
})
await Promise.all( await Promise.all(
allAdUsers.map(async user => allAdUsers.map(async user =>
@ -343,7 +365,10 @@ class User {
) )
) )
console.log(`${allAdUsers.length} usuários importados`) logSuccess({
tags: ['user'],
message: `${allAdUsers.length} usuários importados`
})
return allAdUsers.length return allAdUsers.length
} catch (e) { } catch (e) {

View File

@ -1,51 +1,78 @@
import cron from 'node-cron' import cron from 'node-cron'
import { updateDevicesInfo } from './lib/wifiDevices' import { updateDevicesInfo } from './lib/wifiDevices'
import { User } from './classes/User' import { User } from './classes/User'
import { format } from 'date-fns'
import oui from 'oui' import oui from 'oui'
import { log } from './lib/logger' import { deleteOldLogs, log, logInfo, logSuccess } from './lib/logger'
import { updateUserIdMappings } from './lib/paloalto' import { updateUserIdMappings } from './lib/paloalto'
function cronLog(message) { logInfo({
log({ tags: ['cron'],
level: 'INFO', message: 'Scheduling tasks...'
tags: ['cron'], })
message,
data: { message }
})
}
cronLog('Scheduling tasks...')
cron.schedule('*/1 * * * *', async () => { cron.schedule('*/1 * * * *', async () => {
cronLog('updateDevicesInfo started.') logInfo({
tags: ['cron', 'wifiDevices'],
message: 'updateDevicesInfo started'
})
const devices = await updateDevicesInfo() const devices = await updateDevicesInfo()
cronLog(`updateDevicesInfo updated ${devices} devices.`) logSuccess({
tags: ['cron', 'wifiDevices'],
message: `updateDevicesInfo updated ${devices} devices`
})
let mappings = 0 let mappings = 0
if (devices > 0) { if (devices > 0) {
cronLog('updateUserIdMappings started.') logInfo({
tags: ['cron', 'user-id'],
message: `updateUserIdMappings started`
})
mappings = await updateUserIdMappings() mappings = await updateUserIdMappings()
cronLog(`updateUserIdMappings updated ${mappings} user-id mappings.`)
logSuccess({
tags: ['cron', 'user-id'],
message: `updateUserIdMappings updated ${mappings} user-id mappings`
})
} }
}) })
cron.schedule( cron.schedule(
'0 0 0 * * *', '0 0 0 * * *',
async () => { async () => {
cronLog('User.importAllUsers started') logInfo({
tags: ['cron', 'user'],
message: `User.importAllUsers started`
})
await User.importAllUsers() await User.importAllUsers()
cronLog('User.importAllUsers finished')
logSuccess({
tags: ['cron', 'user'],
message: `User.importAllUsers finished`
})
}, },
{} {}
) )
cron.schedule('0 0 0 * * *', async () => { cron.schedule('0 0 0 * * *', async () => {
await oui.update() await oui.update()
cronLog('Oui updated') logSuccess({
tags: ['cron', 'oui'],
message: `OUI list updated`
})
})
cron.schedule('0 0 0 * * *', async () => {
await deleteOldLogs()
logSuccess({
tags: ['cron', 'log'],
message: `Old logs deleted`
})
}) })

View File

@ -1,21 +1,27 @@
import {} from 'dotenv/config' import {} from 'dotenv/config'
import '@babel/polyfill/noConflict' import '@babel/polyfill/noConflict'
import './utils/capitalize' import './utils/capitalize'
import { logInfo, logSuccess } from './lib/logger'
import { server } from './server' import { server } from './server'
import './cronTasks' import './cronTasks'
console.log( logInfo({
process.env.NODE_ENV === 'production' tags: ['server'],
? '[Running in production]' level: 'SUCCESS',
: '[Running in development]' message:
) process.env.NODE_ENV === 'production'
? 'Running in production'
: 'Running in development'
})
server.listen().then(options => { server.listen().then(options => {
console.log( logSuccess({
`\n---\nServer ready!`, tags: ['server'],
`\nEndpoint: ${options.url}graphql`, message: `Server ready!`
`\nWebSocket: ${options.subscriptionsUrl}\n---` })
) logInfo({
tags: ['server'],
message: `Endpoint: ${options.url}graphql - WebSocket: ${options.subscriptionsUrl}`
})
}) })

View File

@ -2,6 +2,7 @@ import config from './config'
import { createClient, Change } from 'ldapjs' import { createClient, Change } from 'ldapjs'
import { User } from '../../classes/User' import { User } from '../../classes/User'
import { encodePassword } from './encodePassword' import { encodePassword } from './encodePassword'
import { logError, logSuccess } from '../logger'
const replacePassword = (username, newPassword) => { const replacePassword = (username, newPassword) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -45,11 +46,20 @@ const replacePassword = (username, newPassword) => {
(err, result) => { (err, result) => {
if (err) { if (err) {
client.unbind(() => { client.unbind(() => {
console.log('Client unbinded due error.') logError({
tags: ['user', 'replacePassword'],
message: 'Error raplacing password',
data: err
})
}) })
reject(new Error(err.message)) reject(new Error(err.message))
} else { } else {
User.upsertUser(username) User.upsertUser(username)
logSuccess({
tags: ['user', 'replacePassword'],
message: `Password updated for user ${username}`,
data: result
})
resolve('Senha alterada com sucesso!') resolve('Senha alterada com sucesso!')
} }
} }

View File

@ -1,6 +1,7 @@
import { create } from 'axios' import { create } from 'axios'
import https from 'https' import https from 'https'
import { ouiFinder } from '../utils/ouiFinder' import { ouiFinder } from '../utils/ouiFinder'
import { logError } from './logger'
const httpsAgent = new https.Agent({ const httpsAgent = new https.Agent({
rejectUnauthorized: false, rejectUnauthorized: false,
@ -37,7 +38,11 @@ async function getDevices() {
return devices return devices
} catch (e) { } catch (e) {
console.log('[Cisco Controller]', e.message) logError({
tags: ['cisco', 'wifiDevices'],
message: e.message,
data: e
})
return [] return []
} }
} }

View File

@ -1,5 +1,5 @@
import prisma from '../prisma' import prisma from '../prisma'
import { format } from 'date-fns' import { format, subDays } from 'date-fns'
async function log({ level, tags = [], message = '', data }) { async function log({ level, tags = [], message = '', data }) {
const logEntry = await prisma.log.create({ const logEntry = await prisma.log.create({
@ -7,7 +7,7 @@ async function log({ level, tags = [], message = '', data }) {
level, level,
tags, tags,
message, message,
data data: { ...data, msg: message }
} }
}) })
@ -19,11 +19,37 @@ async function log({ level, tags = [], message = '', data }) {
ERROR: '\x1b[31m' ERROR: '\x1b[31m'
}[logEntry.level] }[logEntry.level]
const entryTags = logEntry.tags.length ? ` [${logEntry.tags}] ` : ''
console.log( console.log(
`${color}[${format(logEntry.timestamp, 'HH:mm:ss')}] [${ `${color}[${format(logEntry.timestamp, 'HH:mm:ss')}]${entryTags}\x1b[0m${
logEntry.tags logEntry.message
}] \x1b[0m ${logEntry.message}` }`
) )
} }
export { log } function logLow({ tags, message, data }) {
log({ level: 'LOW', tags: tags, message, data })
}
function logInfo({ tags, message, data }) {
log({ level: 'INFO', tags: tags, message, data })
}
function logSuccess({ tags, message, data }) {
log({ level: 'SUCCESS', tags: tags, message, data })
}
function logWarning({ tags, message, data }) {
log({ level: 'WARNING', tags: tags, message, data })
}
function logError({ tags, message, data }) {
log({ level: 'ERROR', tags: tags, message, data })
}
async function deleteOldLogs() {
return prisma.log.deleteMany({
where: { timestamp: { lt: subDays(new Date(), 30) } }
})
}
export { log, logLow, logInfo, logSuccess, logWarning, logError, deleteOldLogs }

View File

@ -5,6 +5,7 @@ import prisma from '../prisma'
import https from 'https' import https from 'https'
import { subMinutes } from 'date-fns' import { subMinutes } from 'date-fns'
import qs from 'qs' import qs from 'qs'
import { logError } from './logger'
const DEBOUNCE_TIME_IN_MS = 5000 const DEBOUNCE_TIME_IN_MS = 5000
const TIMEOUT_IN_MINUTES = '3' const TIMEOUT_IN_MINUTES = '3'
@ -72,7 +73,12 @@ async function updateUserIdMappings() {
return wifiDevices.length return wifiDevices.length
} catch (e) { } catch (e) {
console.log('Error updating user-id mappings:', e.message) logError({
tags: ['paloalto', 'user-id'],
message: `Error updating user-id mappings: ${e.message}`,
data: e
})
return 'Não foi possível atualizar. Veja o log do servidor' return 'Não foi possível atualizar. Veja o log do servidor'
} finally { } finally {
setTimeout(() => { setTimeout(() => {

View File

@ -5,6 +5,7 @@ import { getOnlineWifiDevices as getOnlineCiscoDevices } from './ciscoController
import prisma from '../prisma' import prisma from '../prisma'
import { pubsub, USER_PRESENCE_UPDATED } from '../pubsub' import { pubsub, USER_PRESENCE_UPDATED } from '../pubsub'
import { logError } from './logger'
const DEBOUNCE_TIME_MS = 10000 const DEBOUNCE_TIME_MS = 10000
const RECENT_THRESHOLD_IN_MINUTES = 3 const RECENT_THRESHOLD_IN_MINUTES = 3
@ -83,8 +84,11 @@ async function updateDB(onlineDevices) {
} }
}) })
} catch (e) { } catch (e) {
if (!['P2016'].includes(e.code)) logError({
console.log('[wifiDevice upsert error]', e) tags: ['wifiDevices'],
message: `Error trying to upsert device with mac "${device.mac}": ${e.message}`,
data: { error: e, device }
})
} }
} }
} }
@ -107,7 +111,12 @@ async function updateDevicesInfo() {
return onlineDevices.length return onlineDevices.length
} catch (e) { } catch (e) {
console.log('Error updating Wi-Fi devices: ', e) logError({
tags: ['wifiDevices'],
message: `Error updating Wi-Fi devices: ${e.message}`,
data: e
})
return 0 return 0
} finally { } finally {
setTimeout(() => { setTimeout(() => {