🏗️」 wip: ELK workingggggggggggggggggggggggggggggggggggg

This commit is contained in:
2025-07-26 15:21:34 +02:00
parent f1d54de6a5
commit 18e41b5552
22 changed files with 116 additions and 103 deletions

View File

@ -1,6 +1,5 @@
import fastifyJWT from '@fastify/jwt';
import fastifyCookie from '@fastify/cookie';
import client from 'prom-client';
import { register } from './register.js';
import { login } from './login.js';
@ -14,7 +13,6 @@ import { totpVerify } from './totpVerify.js';
const saltRounds = 10;
export const appName = process.env.APP_NAME || 'knl_meowscendence';
const collectDefaultMetrics = client.collectDefaultMetrics
authDB.prepareDB();
@ -24,29 +22,6 @@ authDB.prepareDB();
*/
export default async function(fastify, options) {
collectDefaultMetrics({ labels: { service: "auth-api" } })
client.register.setDefaultLabels({ service: "auth-api" })
const httpRequestCounter = new client.Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
labelNames: ['method', 'route', 'status_code'],
})
fastify.addHook('onResponse', (req, res, done) => {
httpRequestCounter.inc({
method: req.method,
route: req.routerPath || req.url,
status_code: res.statusCode,
})
done()
})
fastify.get('/metrics', async (req, reply) => {
reply
.header('Content-Type', client.register.contentType)
.send(await client.register.metrics())
})
fastify.register(fastifyJWT, {
secret: process.env.JWT_SECRET || '123456789101112131415161718192021',
cookie: {

View File

@ -1,10 +1,8 @@
import fastifyJWT from '@fastify/jwt';
import fastifyCookie from '@fastify/cookie';
import Database from 'better-sqlite3';
import client from 'prom-client';
var env = process.env.NODE_ENV || 'development';
const collectDefaultMetrics = client.collectDefaultMetrics
let database;
@ -58,31 +56,6 @@ const deleteFriends = database.prepare('DELETE FROM friends WHERE username = ?;'
* @param {import('fastify').FastifyPluginOptions} options
*/
export default async function(fastify, options) {
collectDefaultMetrics({ labels: { service: "auth-api" } })
client.register.setDefaultLabels({ service: "auth-api" })
const httpRequestCounter = new client.Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
labelNames: ['method', 'route', 'status_code'],
})
fastify.addHook('onResponse', (req, res, done) => {
httpRequestCounter.inc({
method: req.method,
route: req.routerPath || req.url,
status_code: res.statusCode,
})
done()
})
fastify.get('/metrics', async (req, reply) => {
reply
.header('Content-Type', client.register.contentType)
.send(await client.register.metrics())
})
fastify.register(fastifyJWT, {
secret: process.env.JWT_SECRET || '123456789101112131415161718192021',
cookie: {

View File

@ -1,53 +1,71 @@
import Fastify from 'fastify';
import authApi from './api/auth/default.js';
import userApi from './api/user/default.js';
import fs from 'fs';
import path from 'path';
const loggerOption = {
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'HH:MM:ss',
ignore: 'pid,hostname'
}
},
file: process.env.LOG_TARGET || ""
const isProduction = process.env.NODE_ENV === 'production';
const logFilePath = process.env.LOG_FILE_PATH || './logs/api.log';
const loggerOption = () => {
if (!isProduction) {
return {
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'HH:MM:ss',
ignore: 'pid,hostname',
},
},
};
} else {
// Make sure the directory exists
const logDir = path.dirname(logFilePath);
fs.mkdirSync(logDir, { recursive: true });
const logStream = fs.createWriteStream(logFilePath, { flags: 'a' }); // append mode
return {
level: 'info',
stream: logStream,
};
}
};
function sigHandle(signal) {
process.exit(0);
}
process.on('SIGINT', sigHandle);
async function start() {
const target = process.env.API_TARGET || 'all';
const servers = [];
if (target === 'auth' || target === 'all') {
const auth = Fastify({ logger: loggerOption });
const auth = Fastify({ logger: loggerOption('auth') });
auth.register(authApi);
if (target !== 'all') {
await auth.listen({ port: 3000, host: '0.0.0.0' });
console.log('Auth API listening on http://0.0.0.0:3000');
}
else {
await auth.listen({ port: 3001, host: '127.0.0.1'});
console.log('Auth API listening on http://localhost:3001');
}
const port = target === 'all' ? 3001 : 3000;
const host = target === 'all' ? '127.0.0.1' : '0.0.0.0';
await auth.listen({ port, host });
console.log(`Auth API listening on http://${host}:${port}`);
servers.push(auth);
}
if (target === 'user' || target === 'all') {
const user = Fastify({ logger: loggerOption });
const user = Fastify({ logger: loggerOption('user') });
user.register(userApi);
if (target !== 'all') {
await user.listen({ port: 3000, host: '0.0.0.0' });
console.log('User API listening on http://0.0.0.0:3000');
}
else {
await user.listen({ port: 3002, host: '127.0.0.1'});
console.log('User API listening on http://localhost:3002');
}
const port = target === 'all' ? 3002 : 3000;
const host = target === 'all' ? '127.0.0.1' : '0.0.0.0';
await user.listen({ port, host });
console.log(`User API listening on http://${host}:${port}`);
servers.push(user);
}
// Graceful shutdown on SIGINT
process.on('SIGINT', async () => {
console.log('SIGINT received, closing servers...');
await Promise.all(servers.map((srv) => srv.close()));
process.exit(0);
});
}
start().catch(console.error);
start().catch((err) => {
console.error(err);
process.exit(1);
});