Skip to content

Commit

Permalink
Implement basic logging
Browse files Browse the repository at this point in the history
  • Loading branch information
megastary committed Oct 18, 2023
1 parent 9292dc9 commit 0f994cb
Show file tree
Hide file tree
Showing 9 changed files with 349 additions and 16 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ config/*.pem
database-backup/*.tar.gz

# Logs
logs
logs/*.log
logs/*.json
*.log
npm-debug.log*
yarn-debug.log*
Expand Down
3 changes: 2 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\bin\\www"
"program": "${workspaceFolder}\\bin\\www",
"outputCapture": "std"
}
]
}
37 changes: 32 additions & 5 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// Require all neccesary modules
import logger from './functions/logger.js'
logger.info('server.app.startup__Importing root modules.')
import morgan from 'morgan'
import createError from 'http-errors' // Generating errors
import express, { json, urlencoded } from 'express' // Express
import methodOverride from 'method-override'
Expand All @@ -11,22 +14,26 @@ import { allowInsecurePrototypeAccess } from '@handlebars/allow-prototype-access
import mongoose from 'mongoose' // database
import connectMongo from 'connect-mongo' // (expressSession)
import passport from 'passport' // authentication method
import 'dotenv/config'

import https from 'https' // Using HTTPS for debug
import fs from 'fs' // Loading certificate from file for debug
import { fileURLToPath } from 'url'
import 'dotenv/config'

// Emulate CommonJS variable
const __dirname = path.dirname(fileURLToPath(import.meta.url))

// Functions
logger.info('server.app.startup__Importing functions.')
import './functions/azure-passport.js'

// Import scheduled tasks
logger.info('server.app.startup__Importing scheduled tasks.')
import './tasks/daily-report.js'
import './tasks/daily-backup.js'

// Load routes from routes folder to later app.use them.
// Access for all
logger.info('server.app.startup__Importing routes.')
import indexRouter from './routes/index.js'
import aboutRouter from './routes/about.js'
import changelogRouter from './routes/changelog.js'
Expand Down Expand Up @@ -57,8 +64,10 @@ import keypadOrderRouter from './routes/api/keypadOrder.js'
import customerName from './routes/api/customerName.js'

// Express app and database connection
const app = express()
logger.info('server.app.startup__Connecting to MongoDB server.')
mongoose.connect(process.env.DB_CONNECTION_STRING)
logger.info('server.app.startup__Creating and configuring Express.js server.')
const app = express()

// View engine setup
app.engine(
Expand All @@ -72,6 +81,13 @@ app.engine(
app.enable('trust proxy')
app.set('view engine', '.hbs')
app.enable('view cache')
// Stream logs to winston
app.use(
morgan(
'server.app.middleware__:remote-addr :remote-user :method :url :status :res[content-length] :referrer',
{ stream: logger.stream }
)
)
app.use(methodOverride())
app.use(json())
app.use(express.static(join(__dirname, 'public')))
Expand Down Expand Up @@ -105,6 +121,7 @@ app.use(passport.session())

// Application routes
// Access for all
logger.info('server.app.startup__Registering routes.')
app.use('/', indexRouter)
app.use('/about', aboutRouter)
app.use('/changelog', changelogRouter)
Expand Down Expand Up @@ -153,14 +170,24 @@ app.use(function (err, req, res, next) {
res.render('error')
})

if (process.env.DEBUG.toLowerCase() === 'true') {
// When testing, we want to use self sign for localhost website. In production we rely on reverse proxy (nginx/apache etc.)
if (process.env.NODE_ENV.toLowerCase() === 'development') {
// When testing, we want to use self signed certificates for localhost website. In production we rely on reverse proxy (nginx/apache etc.)
const options = {
key: fs.readFileSync('./config/key.pem'),
cert: fs.readFileSync('./config/cert.pem')
}
// Create an HTTPS service identical to the HTTP service.
logger.warn(
'server.app.startup__Creating HTTPS server for development - DO NOT use in PRODUCTION, use reverse proxy instead!'
)
https.createServer(options, app).listen(process.env.APP_PORT_SSL || 443)
logger.info(
`server.app.startup__HTTPS server listening on port ${
process.env.APP_PORT_SSL || 443
}`
)
}

logger.info('server.app.startup__Application started!')

export default app
13 changes: 9 additions & 4 deletions bin/www.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
import app from '../app.js'
import debug from 'debug'
import { createServer } from 'http'

const logger = debug('small-bussiness-fridge:server')
import logger from '../functions/logger.js'
const defaultLogger = debug('small-bussiness-fridge:server')

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000')
var port = normalizePort(process.env.APP_PORT || '3000')
app.set('port', port)

/**
Expand Down Expand Up @@ -66,9 +66,13 @@ function onError(error) {
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges')
logger.error(
`server.www.startup__Specified port requires elevated privileges.`
)
process.exit(1)
case 'EADDRINUSE':
console.error(bind + ' is already in use')
logger.error(`server.www.startup__Specified port is already in use.`)
process.exit(1)
default:
throw error
Expand All @@ -82,5 +86,6 @@ function onError(error) {
function onListening() {
var addr = server.address()
var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port
logger('Listening on ' + bind)
defaultLogger('Listening on ' + bind)
logger.info(`server.www.startup__HTTP server listening on port ${port}`)
}
32 changes: 32 additions & 0 deletions functions/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { createLogger, transports, format } from 'winston'
const { combine, timestamp, json, simple } = format

var logger = createLogger({
transports: [
new transports.File({
format: combine(timestamp(), json()),
level: 'info',
filename: './logs/all-logs.json',
handleExceptions: true,
json: true,
maxsize: 5242880, //5MB
maxFiles: 14,
colorize: false
}),
new transports.Console({
format: simple(),
level: 'debug',
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false
})

logger.stream = {
write: function (message, _encoding) {
logger.info(message.replace(/(\n)/gm, ''))
}
}
export default logger
2 changes: 1 addition & 1 deletion functions/sendMail.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createTransport } from 'nodemailer'
export function sendMail(mailto, mailsubject, mailbody, image) {
// In case mail is destined for system administrator or we run in development environment, send all e-mails to system address obtained from config.
if (process.env.NODE_ENV === 'development' || mailto === 'system@system') {
mailto = process.env.MAIL_SYSTEM
mailto = process.env.MAIL_SYSTEM || 'root@localhost'
}

var transporter = createTransport({
Expand Down
Empty file added logs/.gitkeep
Empty file.
Loading

0 comments on commit 0f994cb

Please sign in to comment.