Skip to content

Commit

Permalink
chore: Use Logger instead of console
Browse files Browse the repository at this point in the history
  • Loading branch information
Dschoordsch committed Dec 9, 2024
1 parent 3d899d3 commit 08273c1
Show file tree
Hide file tree
Showing 18 changed files with 44 additions and 26 deletions.
3 changes: 2 additions & 1 deletion packages/server/billing/debug.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// call with yarn sucrase-node billing/debug.ts
import '../../../scripts/webpack/utils/dotenv'
import {getStripeManager} from '../utils/stripe'
import {Logger} from '../utils/Logger'

const doDebugStuff = async () => {
const manager = getStripeManager()
const res = await manager.updateSubscriptionQuantity('foo', 39, 1597966749)
console.log('res', {res})
Logger.log('res', {res})
}

doDebugStuff()
2 changes: 1 addition & 1 deletion packages/server/dataloader/customLoaderMakers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -880,7 +880,7 @@ export const featureFlagByOwnerId = (parent: RootDataLoader) => {

const missingFeatureNames = featureNames.filter((name) => !existingFeatureNameSet.has(name))
if (missingFeatureNames.length > 0) {
console.error(
Logger.error(
`Feature flag name(s) not found: ${missingFeatureNames.join(', ')}. Add the feature flag name with the addFeatureFlag mutation.`
)
}
Expand Down
3 changes: 2 additions & 1 deletion packages/server/debugJira.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// call with yarn sucrase-node debugJira.ts
import '../../scripts/webpack/utils/dotenv'
import AtlassianServerManager from './utils/AtlassianServerManager'
import {Logger} from './utils/Logger'

const debugJira = async () => {
// const cloudId = "foo"
Expand All @@ -12,7 +13,7 @@ const debugJira = async () => {
if (res instanceof Error) return
const manager = new AtlassianServerManager(res.accessToken)
const screens = await manager.getCloudNameLookup()
console.log(JSON.stringify(screens))
Logger.log(JSON.stringify(screens))
}

debugJira()
5 changes: 3 additions & 2 deletions packages/server/email/MailManagerDebug.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import fs from 'fs'
import MailManager, {MailManagerOptions} from './MailManager'
import {Logger} from '../utils/Logger'

export default class MailManagerDebug extends MailManager {
async sendEmail(options: MailManagerOptions) {
const {to, subject, body} = options
console.warn(`SENDING EMAIL
Logger.warn(`SENDING EMAIL
To: ${to}
Subject: ${subject}
Body: ${body}`)
Expand All @@ -17,7 +18,7 @@ export default class MailManagerDebug extends MailManager {
const folder = '/tmp'
fs.writeFileSync(`${folder}/${filename}`, html)
// make it a link so you can click it in the terminal
console.warn(`Wrote email to file://${folder}/${encodeURIComponent(filename)}`)
Logger.warn(`Wrote email to file://${folder}/${encodeURIComponent(filename)}`)
return true
}
}
4 changes: 3 additions & 1 deletion packages/server/fileStorage/LocalFileStoreManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import makeAppURL from 'parabol-client/utils/makeAppURL'
import path from 'path'
import appOrigin from '../appOrigin'
import FileStoreManager from './FileStoreManager'
import {Logger} from '../utils/Logger'

export default class LocalFileStoreManager extends FileStoreManager {
baseUrl = makeAppURL(appOrigin, 'self-hosted')
constructor() {
Expand Down Expand Up @@ -33,7 +35,7 @@ export default class LocalFileStoreManager extends FileStoreManager {
}

async putBuildFile() {
console.error(
Logger.error(
'Cannot call `putBuildFile` when using Local File Storage. The build files are already there'
)
return ''
Expand Down
3 changes: 2 additions & 1 deletion packages/server/fileStorage/S3FileStoreManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {StandardRetryStrategy} from '@smithy/util-retry'
import mime from 'mime-types'
import path from 'path'
import FileStoreManager, {FileAssetDir} from './FileStoreManager'
import {Logger} from '../utils/Logger'

class CloudflareRetry extends StandardRetryStrategy {
public async refreshRetryTokenForRetry(
Expand All @@ -14,7 +15,7 @@ class CloudflareRetry extends StandardRetryStrategy {
const status = errorInfo.error?.$response?.statusCode
if (status && status >= 520 && status < 530) {
const date = errorInfo.error?.$response?.headers?.date
console.log('Retrying after Cloudflare error', {
Logger.log('Retrying after Cloudflare error', {
status,
date: date && new Date(date).toISOString(),
path: errorInfo.error?.$response?.body?.req?.path
Expand Down
3 changes: 2 additions & 1 deletion packages/server/graphql/composeResolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {allow} from 'graphql-shield'
import type {ShieldRule} from 'graphql-shield/dist/types'
import hash from 'object-hash'
import {ResolverFn} from './private/resolverTypes'
import {Logger} from '../utils/Logger'

type Resolver = ResolverFn<any, any, any, any>

Expand Down Expand Up @@ -43,7 +44,7 @@ const wrapResolve =
return res
}
} catch (err) {
console.log(err)
Logger.log(err)
throw err
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import getKysely from '../../../postgres/getKysely'
import getPg from '../../../postgres/getPg'
import getPgConfig from '../../../postgres/getPgConfig'
import {MutationResolvers} from '../resolverTypes'
import {Logger} from '../../../utils/Logger'

const exec = util.promisify(childProcess.exec)

Expand All @@ -23,7 +24,7 @@ const dumpPgDataToOrgBackupSchema = async (orgIds: string[]) => {
.where('removedAt', 'is', null)
.execute()
const userIds = orgUsers.map(({userId}) => userId)
console.log({teamIds, userIds})
Logger.log({teamIds, userIds})

// try {
// // do all inserts here
Expand Down
3 changes: 2 additions & 1 deletion packages/server/graphql/private/queries/orgActivities.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {sql} from 'kysely'
import getKysely from '../../../postgres/getKysely'
import {OrgActivityRow, QueryResolvers} from '../resolverTypes'
import {Logger} from '../../../utils/Logger'

const orgActivities: QueryResolvers['orgActivities'] = async (_source, {startDate, endDate}) => {
const pg = getKysely()
Expand Down Expand Up @@ -100,7 +101,7 @@ const orgActivities: QueryResolvers['orgActivities'] = async (_source, {startDat
const rows = Object.values(combinedResults)
return {rows}
} catch (error) {
console.error('Error executing Org Activity Report:', error)
Logger.error('Error executing Org Activity Report:', error)
return {error: {message: 'Error executing Org Activity Report'}}
}
}
Expand Down
3 changes: 2 additions & 1 deletion packages/server/jiraImagesHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import jiraPlaceholder from '../../static/images/illustrations/imageNotFound.png
import sleep from '../client/utils/sleep'
import uWSAsyncHandler from './graphql/uWSAsyncHandler'
import getRedis, {RedisPipelineResponse} from './utils/getRedis'
import {Logger} from './utils/Logger'

const getImageFromCache = async (
imgUrlHash: string,
Expand Down Expand Up @@ -33,7 +34,7 @@ const servePlaceholderImage = async (res: HttpResponse) => {
const res = await fetch(jiraPlaceholder)
jiraPlaceholderBuffer = Buffer.from(await res.arrayBuffer())
} catch (e) {
console.error('Jira Placeholder image could not be fetched', e)
Logger.error('Jira Placeholder image could not be fetched', e)
}
}
res.writeStatus('200').writeHeader('Content-Type', 'image/png').end(jiraPlaceholderBuffer)
Expand Down
5 changes: 3 additions & 2 deletions packages/server/listenHandler.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import {us_listen_socket} from 'uWebSockets.js'
import getGraphQLExecutor from './utils/getGraphQLExecutor'
import serverHealthChecker from './utils/serverHealthChecker'
import {Logger} from './utils/Logger'

const listenHandler = (listenSocket: us_listen_socket) => {
const PORT = Number(__PRODUCTION__ ? process.env.PORT : process.env.SOCKET_PORT)
const SERVER_ID = process.env.SERVER_ID
if (listenSocket) {
console.log(`\n🔥🔥🔥 Server ID: ${SERVER_ID}. Ready for Sockets: Port ${PORT} 🔥🔥🔥`)
Logger.log(`\n🔥🔥🔥 Server ID: ${SERVER_ID}. Ready for Sockets: Port ${PORT} 🔥🔥🔥`)
getGraphQLExecutor().subscribe()
// Cleaning on startup because shutdowns may be abrupt
serverHealthChecker.cleanUserPresence()
} else {
console.log(`❌❌❌ Port ${PORT} is in use! ❌❌❌`)
Logger.log(`❌❌❌ Port ${PORT} is in use! ❌❌❌`)
}
}

Expand Down
5 changes: 3 additions & 2 deletions packages/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import SSEConnectionHandler from './sse/SSEConnectionHandler'
import SSEPingHandler from './sse/SSEPingHandler'
import staticFileHandler from './staticFileHandler'
import SAMLHandler from './utils/SAMLHandler'
import {Logger} from './utils/Logger'

tracer.init({
service: `web`,
Expand All @@ -33,7 +34,7 @@ tracer.init({
tracer.use('ioredis').use('http').use('pg')

process.on('SIGTERM', async (signal) => {
console.log(
Logger.log(
`Server ID: ${process.env.SERVER_ID}. Kill signal received: ${signal}, starting graceful shutdown.`
)
const RECONNECT_WINDOW = 60_000 // ms
Expand All @@ -44,7 +45,7 @@ process.on('SIGTERM', async (signal) => {
await handleDisconnect(connectionContext)
})
)
console.log(`Server ID: ${process.env.SERVER_ID}. Graceful shutdown complete, exiting.`)
Logger.log(`Server ID: ${process.env.SERVER_ID}. Graceful shutdown complete, exiting.`)
process.exit()
})

Expand Down
5 changes: 3 additions & 2 deletions packages/server/staticFileHandler.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import {HttpRequest, HttpResponse} from 'uWebSockets.js'
import acceptsBrotli from './acceptsBrotli'
import serveStatic from './utils/serveStatic'
import {Logger} from './utils/Logger'

const ROUTE = '/static/'
let hasWarned = false
const staticFileHandler = async (res: HttpResponse, req: HttpRequest) => {
if (__PRODUCTION__ && !hasWarned) {
hasWarned = true
console.log(
Logger.log(
'Using NodeJS to serve static assets. This is slow! Your reverse proxy should redirect /static to a CDN'
)
console.log(req.getUrl())
Logger.log(req.getUrl())
}
const fileName = req.getUrl().slice(ROUTE.length)
const servedStatic = serveStatic(res, fileName, acceptsBrotli(req))
Expand Down
3 changes: 2 additions & 1 deletion packages/server/utils/getRedisOptions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {readFileSync} from 'fs'
import path from 'node:path'
import getProjectRoot from '../../../scripts/webpack/utils/getProjectRoot'
import {Logger} from './Logger'

const getAbsPath = (maybeRelativePath: string) => {
if (path.isAbsolute(maybeRelativePath)) return maybeRelativePath
Expand Down Expand Up @@ -54,7 +55,7 @@ export const getRedisOptions = () => {
const mode = getMode(tls, password)
// Keep logs quiet if using default
if (mode !== 'Unsecure') {
console.log(`Redis mode: ${mode}`)
Logger.log(`Redis mode: ${mode}`)
}
return {tls, password}
}
3 changes: 2 additions & 1 deletion packages/server/utils/sendToSentry.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as Sentry from '@sentry/node'
import {getUserById} from '../postgres/queries/getUsersByIds'
import {Logger} from './Logger'

export interface SentryOptions {
sampleRate?: number
Expand All @@ -13,7 +14,7 @@ export interface SentryOptions {

// Even though this is a promise we'll never need to await it, so we'll never need to worry about catching an error
const sendToSentry = async (error: Error, options: SentryOptions = {}) => {
console.log('SEND TO SENTRY', error || JSON.stringify(error))
Logger.log('SEND TO SENTRY', error || JSON.stringify(error))
const {sampleRate, tags, extras, userId, ip} = options
if (sampleRate && Math.random() > sampleRate) return
const fullUser = userId ? await getUserById(userId) : null
Expand Down
3 changes: 2 additions & 1 deletion packages/server/utils/serverHealthChecker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {disconnectQuery} from '../socketHandlers/handleDisconnect'
import RedisInstance from './RedisInstance'
import publishInternalGQL from './publishInternalGQL'
import sendToSentry from './sendToSentry'
import {Logger} from './Logger'

const SERVER_ID = process.env.SERVER_ID!
const INSTANCE_ID = `${SERVER_ID}:${process.pid}`
Expand All @@ -24,7 +25,7 @@ class ServerHealthChecker {
this.publisher.publish(`socketServerPong:${remoteServerId}`, INSTANCE_ID)
} else if (channel === `socketServerPong:${INSTANCE_ID}`) {
if (!this.remoteSocketServers) {
console.error('unsolicited pong received before getLivingServers was called')
Logger.error('unsolicited pong received before getLivingServers was called')
} else {
this.remoteSocketServers.push(remoteServerId)
}
Expand Down
11 changes: 6 additions & 5 deletions packages/server/utils/startMemwatch.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
const memwatch = require('memwatch-next')
const fs = require('fs')
const path = require('path')
import {Logger} from './Logger'

const startMemwatch = () => {
console.log('starting memwatch')
Logger.log('starting memwatch')
memwatch.on('leak', (info) => {
console.error('Mem leak detected', info)
Logger.error('Mem leak detected', info)
})
let snapStart
let snapStop
let heapDiff
memwatch.on('stats', (stats) => {
console.log(stats.current_base)
Logger.log(stats.current_base)
if (stats.current_base > 137062320 && stats.current_base < 139000000 && !snapStart) {
snapStart = true
console.log('startMemwatch heapDiff')
Logger.log('startMemwatch heapDiff')
heapDiff = new memwatch.HeapDiff()
}
if (stats.current_base > 145000000 && snapStart && !snapStop) {
snapStop = true
const end = heapDiff.end()
console.log('heapDiff end', end)
Logger.log('heapDiff end', end)
const jsonPath = path.join(process.cwd(), 'leak.json')
fs.writeFileSync(jsonPath, JSON.stringify(end, null, 2))
}
Expand Down
3 changes: 2 additions & 1 deletion packages/server/utils/stripe/StubStripeManager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Stripe from 'stripe'
import {toEpochSeconds} from '../epochTime'
import StripeManager from './StripeManager'
import {Logger} from '../Logger'

// using proxy to start gradual coverage of StripeManager
export default function StubStripeManager() {
Expand All @@ -25,7 +26,7 @@ export default function StubStripeManager() {
} as unknown as Stripe.Subscription
}
default:
console.warn('StubStripeManager forwarding to real StripeManager', propKey)
Logger.warn('StubStripeManager forwarding to real StripeManager', propKey)
return target[propKey]
}
}
Expand Down

0 comments on commit 08273c1

Please sign in to comment.