1
0
mirror of https://github.com/MisskeyIO/misskey synced 2024-11-27 22:38:30 +09:00

Use internal logger instead of debug/console for logging

Resolve #4104
Resolve #1966
Resolve #1937
This commit is contained in:
syuilo 2019-02-03 18:16:57 +09:00
parent 3a5867b324
commit 0868c3517f
No known key found for this signature in database
GPG Key ID: BDC4C49D06AB9D69
41 changed files with 136 additions and 109 deletions

View File

@ -31,7 +31,6 @@
"@types/bcryptjs": "2.4.2", "@types/bcryptjs": "2.4.2",
"@types/chai-http": "3.0.5", "@types/chai-http": "3.0.5",
"@types/dateformat": "3.0.0", "@types/dateformat": "3.0.0",
"@types/debug": "0.0.31",
"@types/deep-equal": "1.0.1", "@types/deep-equal": "1.0.1",
"@types/double-ended-queue": "2.1.0", "@types/double-ended-queue": "2.1.0",
"@types/elasticsearch": "5.0.30", "@types/elasticsearch": "5.0.30",
@ -108,7 +107,6 @@
"css-loader": "1.0.1", "css-loader": "1.0.1",
"cssnano": "4.1.8", "cssnano": "4.1.8",
"dateformat": "3.0.3", "dateformat": "3.0.3",
"debug": "4.1.1",
"deep-equal": "1.0.1", "deep-equal": "1.0.1",
"deepcopy": "0.6.3", "deepcopy": "0.6.3",
"diskusage": "1.0.0", "diskusage": "1.0.0",

View File

@ -181,7 +181,7 @@ export default abstract class Chart<T> {
if (e.code === 11000) { if (e.code === 11000) {
log = await this.getLatestLog(span, group); log = await this.getLatestLog(span, group);
} else { } else {
console.error(e); logger.error(e);
throw e; throw e;
} }
} }

View File

@ -60,7 +60,6 @@ async function usedMem() {
const data = await sysUtils.mem(); const data = await sysUtils.mem();
return data.active; return data.active;
} catch (error) { } catch (error) {
console.error(error);
throw error; throw error;
} }
} }
@ -71,7 +70,6 @@ async function totalMem() {
const data = await sysUtils.mem(); const data = await sysUtils.mem();
return data.total; return data.total;
} catch (error) { } catch (error) {
console.error(error);
throw error; throw error;
} }
} }

View File

@ -1,5 +1,8 @@
import * as elasticsearch from 'elasticsearch'; import * as elasticsearch from 'elasticsearch';
import config from '../config'; import config from '../config';
import Logger from '../misc/logger';
const esLogger = new Logger('es');
const index = { const index = {
settings: { settings: {
@ -50,9 +53,9 @@ if (client) {
requestTimeout: 30000 requestTimeout: 30000
}, error => { }, error => {
if (error) { if (error) {
console.error('elasticsearch is down!'); esLogger.error('elasticsearch is down!');
} else { } else {
console.log('elasticsearch is available!'); esLogger.succ('elasticsearch is available!');
} }
}); });

View File

@ -18,6 +18,7 @@ export default db;
* MongoDB native module (officialy) * MongoDB native module (officialy)
*/ */
import * as mongodb from 'mongodb'; import * as mongodb from 'mongodb';
import Logger from '../misc/logger';
let mdb: mongodb.Db; let mdb: mongodb.Db;
@ -37,3 +38,5 @@ const nativeDbConn = async (): Promise<mongodb.Db> => {
}; };
export { nativeDbConn }; export { nativeDbConn };
export const dbLogger = new Logger('db');

View File

@ -34,6 +34,7 @@ program
.version(pkg.version) .version(pkg.version)
.option('--no-daemons', 'Disable daemon processes (for debbuging)') .option('--no-daemons', 'Disable daemon processes (for debbuging)')
.option('--disable-clustering', 'Disable clustering') .option('--disable-clustering', 'Disable clustering')
.option('--quiet', 'Suppress all logs')
.parse(process.argv); .parse(process.argv);
//#endregion //#endregion
@ -67,11 +68,15 @@ function main() {
async function masterMain() { async function masterMain() {
let config: Config; let config: Config;
if (!program.quiet) {
//#region Misskey logo
console.log(' _____ _ _ '); console.log(' _____ _ _ ');
console.log('| |_|___ ___| |_ ___ _ _ '); console.log('| |_|___ ___| |_ ___ _ _ ');
console.log('| | | | |_ -|_ -| \'_| -_| | |'); console.log('| | | | |_ -|_ -| \'_| -_| | |');
console.log('|_|_|_|_|___|___|_,_|___|_ |'); console.log('|_|_|_|_|___|___|_,_|___|_ |');
console.log(' |___|\n'); console.log(' |___|\n');
//#endregion
}
bootLogger.info('Welcome to Misskey!'); bootLogger.info('Welcome to Misskey!');
bootLogger.info(`Misskey v${pkg.version}`, true); bootLogger.info(`Misskey v${pkg.version}`, true);
@ -80,8 +85,7 @@ async function masterMain() {
// initialize app // initialize app
config = await init(); config = await init();
} catch (e) { } catch (e) {
console.error(e); bootLogger.error('Fatal error occurred during initialization', true);
bootLogger.error('Fatal error occurred during initialization');
process.exit(1); process.exit(1);
} }
@ -191,7 +195,7 @@ async function init(): Promise<Config> {
} }
if (!await isPortAvailable(config.port)) { if (!await isPortAvailable(config.port)) {
bootLogger.error(`Port ${config.port} is already in use`); bootLogger.error(`Port ${config.port} is already in use`, true);
process.exit(1); process.exit(1);
} }
@ -263,7 +267,9 @@ cluster.on('exit', worker => {
}); });
// Display detail of unhandled promise rejection // Display detail of unhandled promise rejection
process.on('unhandledRejection', console.dir); if (!program.quiet) {
process.on('unhandledRejection', console.dir);
}
// Display detail of uncaught exception // Display detail of uncaught exception
process.on('uncaughtException', err => { process.on('uncaughtException', err => {

View File

@ -2,6 +2,8 @@ import * as cluster from 'cluster';
import chalk from 'chalk'; import chalk from 'chalk';
import * as dateformat from 'dateformat'; import * as dateformat from 'dateformat';
const quiet = process.argv.find(x => x == '--quiet');
export default class Logger { export default class Logger {
private domain: string; private domain: string;
private color?: string; private color?: string;
@ -19,6 +21,7 @@ export default class Logger {
} }
public log(level: string, message: string, important = false): void { public log(level: string, message: string, important = false): void {
if (quiet) return;
const domain = this.color ? chalk.keyword(this.color)(this.domain) : chalk.white(this.domain); const domain = this.color ? chalk.keyword(this.color)(this.domain) : chalk.white(this.domain);
if (this.parentLogger) { if (this.parentLogger) {
this.parentLogger.log(level, `[${domain}]\t${message}`, important); this.parentLogger.log(level, `[${domain}]\t${message}`, important);
@ -30,8 +33,8 @@ export default class Logger {
} }
} }
public error(message: string | Error): void { // 実行を継続できない状況で使う public error(message: string | Error, important = false): void { // 実行を継続できない状況で使う
this.log(chalk.red('ERR '), chalk.red(message.toString())); this.log(chalk.red('ERR '), chalk.red(message.toString()), important);
} }
public warn(message: string, important = false): void { // 実行を継続できるが改善すべき状況で使う public warn(message: string, important = false): void { // 実行を継続できるが改善すべき状況で使う

View File

@ -2,7 +2,7 @@ import * as mongo from 'mongodb';
import * as deepcopy from 'deepcopy'; import * as deepcopy from 'deepcopy';
import { pack as packFolder } from './drive-folder'; import { pack as packFolder } from './drive-folder';
import { pack as packUser } from './user'; import { pack as packUser } from './user';
import monkDb, { nativeDbConn } from '../db/mongodb'; import monkDb, { nativeDbConn, dbLogger } from '../db/mongodb';
import isObjectId from '../misc/is-objectid'; import isObjectId from '../misc/is-objectid';
import getDriveFileUrl, { getOriginalUrl } from '../misc/get-drive-file-url'; import getDriveFileUrl, { getOriginalUrl } from '../misc/get-drive-file-url';
@ -171,7 +171,7 @@ export const pack = (
// (データベースの欠損などで)ファイルがデータベース上に見つからなかったとき // (データベースの欠損などで)ファイルがデータベース上に見つからなかったとき
if (_file == null) { if (_file == null) {
console.warn(`[DAMAGED DB] (missing) pkg: driveFile :: ${file}`); dbLogger.warn(`[DAMAGED DB] (missing) pkg: driveFile :: ${file}`);
return resolve(null); return resolve(null);
} }

View File

@ -1,6 +1,6 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import * as deepcopy from 'deepcopy'; import * as deepcopy from 'deepcopy';
import db from '../db/mongodb'; import db, { dbLogger } from '../db/mongodb';
import isObjectId from '../misc/is-objectid'; import isObjectId from '../misc/is-objectid';
import { pack as packNote } from './note'; import { pack as packNote } from './note';
@ -56,7 +56,7 @@ export const pack = (
// (データベースの不具合などで)投稿が見つからなかったら // (データベースの不具合などで)投稿が見つからなかったら
if (_favorite.note == null) { if (_favorite.note == null) {
console.warn(`[DAMAGED DB] (missing) pkg: favorite -> note :: ${_favorite.id} (note ${_favorite.noteId})`); dbLogger.warn(`[DAMAGED DB] (missing) pkg: favorite -> note :: ${_favorite.id} (note ${_favorite.noteId})`);
return resolve(null); return resolve(null);
} }

View File

@ -1,7 +1,7 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import * as deepcopy from 'deepcopy'; import * as deepcopy from 'deepcopy';
import rap from '@prezzemolo/rap'; import rap from '@prezzemolo/rap';
import db from '../db/mongodb'; import db, { dbLogger } from '../db/mongodb';
import isObjectId from '../misc/is-objectid'; import isObjectId from '../misc/is-objectid';
import { length } from 'stringz'; import { length } from 'stringz';
import { IUser, pack as packUser } from './user'; import { IUser, pack as packUser } from './user';
@ -231,7 +231,7 @@ export const pack = async (
// (データベースの欠損などで)投稿がデータベース上に見つからなかったとき // (データベースの欠損などで)投稿がデータベース上に見つからなかったとき
if (_note == null) { if (_note == null) {
console.warn(`[DAMAGED DB] (missing) pkg: note :: ${note}`); dbLogger.warn(`[DAMAGED DB] (missing) pkg: note :: ${note}`);
return null; return null;
} }
@ -367,18 +367,18 @@ export const pack = async (
//#region (データベースの欠損などで)参照しているデータがデータベース上に見つからなかったとき //#region (データベースの欠損などで)参照しているデータがデータベース上に見つからなかったとき
if (_note.user == null) { if (_note.user == null) {
console.warn(`[DAMAGED DB] (missing) pkg: note -> user :: ${_note.id} (user ${_note.userId})`); dbLogger.warn(`[DAMAGED DB] (missing) pkg: note -> user :: ${_note.id} (user ${_note.userId})`);
return null; return null;
} }
if (opts.detail) { if (opts.detail) {
if (_note.replyId != null && _note.reply == null) { if (_note.replyId != null && _note.reply == null) {
console.warn(`[DAMAGED DB] (missing) pkg: note -> reply :: ${_note.id} (reply ${_note.replyId})`); dbLogger.warn(`[DAMAGED DB] (missing) pkg: note -> reply :: ${_note.id} (reply ${_note.replyId})`);
return null; return null;
} }
if (_note.renoteId != null && _note.renote == null) { if (_note.renoteId != null && _note.renote == null) {
console.warn(`[DAMAGED DB] (missing) pkg: note -> renote :: ${_note.id} (renote ${_note.renoteId})`); dbLogger.warn(`[DAMAGED DB] (missing) pkg: note -> renote :: ${_note.id} (renote ${_note.renoteId})`);
return null; return null;
} }
} }

View File

@ -1,6 +1,6 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import * as deepcopy from 'deepcopy'; import * as deepcopy from 'deepcopy';
import db from '../db/mongodb'; import db, { dbLogger } from '../db/mongodb';
import isObjectId from '../misc/is-objectid'; import isObjectId from '../misc/is-objectid';
import { IUser, pack as packUser } from './user'; import { IUser, pack as packUser } from './user';
import { pack as packNote } from './note'; import { pack as packNote } from './note';
@ -106,12 +106,12 @@ export const pack = (notification: any) => new Promise<any>(async (resolve, reje
// (データベースの不具合などで)投稿が見つからなかったら // (データベースの不具合などで)投稿が見つからなかったら
if (_notification.note == null) { if (_notification.note == null) {
console.warn(`[DAMAGED DB] (missing) pkg: notification -> note :: ${_notification.id} (note ${_notification.noteId})`); dbLogger.warn(`[DAMAGED DB] (missing) pkg: notification -> note :: ${_notification.id} (note ${_notification.noteId})`);
return resolve(null); return resolve(null);
} }
break; break;
default: default:
console.error(`Unknown type: ${_notification.type}`); dbLogger.error(`Unknown type: ${_notification.type}`);
break; break;
} }

View File

@ -1,7 +1,7 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import * as deepcopy from 'deepcopy'; import * as deepcopy from 'deepcopy';
import rap from '@prezzemolo/rap'; import rap from '@prezzemolo/rap';
import db from '../db/mongodb'; import db, { dbLogger } from '../db/mongodb';
import isObjectId from '../misc/is-objectid'; import isObjectId from '../misc/is-objectid';
import { packMany as packNoteMany } from './note'; import { packMany as packNoteMany } from './note';
import Following from './following'; import Following from './following';
@ -286,7 +286,7 @@ export const pack = (
// (データベースの欠損などで)ユーザーがデータベース上に見つからなかったとき // (データベースの欠損などで)ユーザーがデータベース上に見つからなかったとき
if (_user == null) { if (_user == null) {
console.warn(`user not found on database: ${user}`); dbLogger.warn(`user not found on database: ${user}`);
return resolve(null); return resolve(null);
} }

View File

@ -44,9 +44,9 @@ export default async function(userId: mongo.ObjectID | string, type: string, bod
push.sendNotification(pushSubscription, JSON.stringify({ push.sendNotification(pushSubscription, JSON.stringify({
type, body type, body
})).catch((err: any) => { })).catch((err: any) => {
//console.log(err.statusCode); //swLogger.info(err.statusCode);
//console.log(err.headers); //swLogger.info(err.headers);
//console.log(err.body); //swLogger.info(err.body);
if (err.statusCode == 410) { if (err.statusCode == 410) {
Subscription.remove({ Subscription.remove({

View File

@ -1,5 +1,6 @@
import http from './processors/http'; import http from './processors/http';
import { ILocalUser } from '../models/user'; import { ILocalUser } from '../models/user';
import Logger from '../misc/logger';
export function createHttpJob(data: any) { export function createHttpJob(data: any) {
return http({ data }, () => {}); return http({ data }, () => {});
@ -15,3 +16,5 @@ export function deliver(user: ILocalUser, content: any, to: any) {
to to
}); });
} }
export const queueLogger = new Logger('queue');

View File

@ -1,6 +1,7 @@
import * as bq from 'bee-queue'; import * as bq from 'bee-queue';
import request from '../../../remote/activitypub/request'; import request from '../../../remote/activitypub/request';
import { queueLogger } from '../..';
export default async (job: bq.Job, done: any): Promise<void> => { export default async (job: bq.Job, done: any): Promise<void> => {
try { try {
@ -13,11 +14,11 @@ export default async (job: bq.Job, done: any): Promise<void> => {
// 何回再送しても成功することはないということなのでエラーにはしないでおく // 何回再送しても成功することはないということなのでエラーにはしないでおく
done(); done();
} else { } else {
console.warn(`deliver failed: ${res.statusCode} ${res.statusMessage} to=${job.data.to}`); queueLogger.warn(`deliver failed: ${res.statusCode} ${res.statusMessage} to=${job.data.to}`);
done(res.statusMessage); done(res.statusMessage);
} }
} else { } else {
console.warn(`deliver failed: ${res} to=${job.data.to}`); queueLogger.warn(`deliver failed: ${res} to=${job.data.to}`);
done(); done();
} }
} }

View File

@ -1,5 +1,6 @@
import deliver from './deliver'; import deliver from './deliver';
import processInbox from './process-inbox'; import processInbox from './process-inbox';
import { queueLogger } from '../..';
const handlers: any = { const handlers: any = {
deliver, deliver,
@ -12,7 +13,7 @@ export default (job: any, done: any) => {
if (handler) { if (handler) {
handler(job, done); handler(job, done);
} else { } else {
console.error(`Unknown job: ${job.data.type}`); queueLogger.error(`Unknown job: ${job.data.type}`);
done(); done();
} }
}; };

View File

@ -1,6 +1,4 @@
import * as bq from 'bee-queue'; import * as bq from 'bee-queue';
import * as debug from 'debug';
import * as httpSignature from 'http-signature'; import * as httpSignature from 'http-signature';
import parseAcct from '../../../misc/acct/parse'; import parseAcct from '../../../misc/acct/parse';
import User, { IRemoteUser } from '../../../models/user'; import User, { IRemoteUser } from '../../../models/user';
@ -9,8 +7,9 @@ import { resolvePerson, updatePerson } from '../../../remote/activitypub/models/
import { toUnicode } from 'punycode'; import { toUnicode } from 'punycode';
import { URL } from 'url'; import { URL } from 'url';
import { publishApLogStream } from '../../../stream'; import { publishApLogStream } from '../../../stream';
import Logger from '../../../misc/logger';
const log = debug('misskey:queue:inbox'); const logger = new Logger('inbox');
// ユーザーのinboxにアクティビティが届いた時の処理 // ユーザーのinboxにアクティビティが届いた時の処理
export default async (job: bq.Job, done: any): Promise<void> => { export default async (job: bq.Job, done: any): Promise<void> => {
@ -21,7 +20,7 @@ export default async (job: bq.Job, done: any): Promise<void> => {
const info = Object.assign({}, activity); const info = Object.assign({}, activity);
delete info['@context']; delete info['@context'];
delete info['signature']; delete info['signature'];
log(info); logger.info(info);
//#endregion //#endregion
const keyIdLower = signature.keyId.toLowerCase(); const keyIdLower = signature.keyId.toLowerCase();
@ -30,7 +29,7 @@ export default async (job: bq.Job, done: any): Promise<void> => {
if (keyIdLower.startsWith('acct:')) { if (keyIdLower.startsWith('acct:')) {
const { username, host } = parseAcct(keyIdLower.slice('acct:'.length)); const { username, host } = parseAcct(keyIdLower.slice('acct:'.length));
if (host === null) { if (host === null) {
console.warn(`request was made by local user: @${username}`); logger.warn(`request was made by local user: @${username}`);
done(); done();
return; return;
} }
@ -39,7 +38,7 @@ export default async (job: bq.Job, done: any): Promise<void> => {
try { try {
ValidateActivity(activity, host); ValidateActivity(activity, host);
} catch (e) { } catch (e) {
console.warn(e.message); logger.warn(e.message);
done(); done();
return; return;
} }
@ -51,7 +50,7 @@ export default async (job: bq.Job, done: any): Promise<void> => {
try { try {
ValidateActivity(activity, host); ValidateActivity(activity, host);
} catch (e) { } catch (e) {
console.warn(e.message); logger.warn(e.message);
done(); done();
return; return;
} }
@ -66,9 +65,9 @@ export default async (job: bq.Job, done: any): Promise<void> => {
if (activity.type === 'Update') { if (activity.type === 'Update') {
if (activity.object && activity.object.type === 'Person') { if (activity.object && activity.object.type === 'Person') {
if (user == null) { if (user == null) {
console.warn('Update activity received, but user not registed.'); logger.warn('Update activity received, but user not registed.');
} else if (!httpSignature.verifySignature(signature, user.publicKey.publicKeyPem)) { } else if (!httpSignature.verifySignature(signature, user.publicKey.publicKeyPem)) {
console.warn('Update activity received, but signature verification failed.'); logger.warn('Update activity received, but signature verification failed.');
} else { } else {
updatePerson(activity.actor, null, activity.object); updatePerson(activity.actor, null, activity.object);
} }
@ -88,7 +87,7 @@ export default async (job: bq.Job, done: any): Promise<void> => {
} }
if (!httpSignature.verifySignature(signature, user.publicKey.publicKeyPem)) { if (!httpSignature.verifySignature(signature, user.publicKey.publicKeyPem)) {
console.warn('signature verification failed'); logger.error('signature verification failed');
done(); done();
return; return;
} }

View File

@ -1,16 +1,15 @@
import * as debug from 'debug';
import Resolver from '../../resolver'; import Resolver from '../../resolver';
import { IRemoteUser } from '../../../../models/user'; import { IRemoteUser } from '../../../../models/user';
import acceptFollow from './follow'; import acceptFollow from './follow';
import { IAccept, IFollow } from '../../type'; import { IAccept, IFollow } from '../../type';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
export default async (actor: IRemoteUser, activity: IAccept): Promise<void> => { export default async (actor: IRemoteUser, activity: IAccept): Promise<void> => {
const uri = activity.id || activity; const uri = activity.id || activity;
log(`Accept: ${uri}`); logger.info(`Accept: ${uri}`);
const resolver = new Resolver(); const resolver = new Resolver();
@ -19,7 +18,7 @@ export default async (actor: IRemoteUser, activity: IAccept): Promise<void> => {
try { try {
object = await resolver.resolve(activity.object); object = await resolver.resolve(activity.object);
} catch (e) { } catch (e) {
log(`Resolution failed: ${e}`); logger.error(`Resolution failed: ${e}`);
throw e; throw e;
} }
@ -29,7 +28,7 @@ export default async (actor: IRemoteUser, activity: IAccept): Promise<void> => {
break; break;
default: default:
console.warn(`Unknown accept type: ${object.type}`); logger.warn(`Unknown accept type: ${object.type}`);
break; break;
} }
}; };

View File

@ -1,16 +1,15 @@
import * as debug from 'debug';
import Resolver from '../../resolver'; import Resolver from '../../resolver';
import { IRemoteUser } from '../../../../models/user'; import { IRemoteUser } from '../../../../models/user';
import announceNote from './note'; import announceNote from './note';
import { IAnnounce, INote } from '../../type'; import { IAnnounce, INote } from '../../type';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
export default async (actor: IRemoteUser, activity: IAnnounce): Promise<void> => { export default async (actor: IRemoteUser, activity: IAnnounce): Promise<void> => {
const uri = activity.id || activity; const uri = activity.id || activity;
log(`Announce: ${uri}`); logger.info(`Announce: ${uri}`);
const resolver = new Resolver(); const resolver = new Resolver();
@ -19,7 +18,7 @@ export default async (actor: IRemoteUser, activity: IAnnounce): Promise<void> =>
try { try {
object = await resolver.resolve(activity.object); object = await resolver.resolve(activity.object);
} catch (e) { } catch (e) {
log(`Resolution failed: ${e}`); logger.error(`Resolution failed: ${e}`);
throw e; throw e;
} }
@ -29,7 +28,7 @@ export default async (actor: IRemoteUser, activity: IAnnounce): Promise<void> =>
break; break;
default: default:
console.warn(`Unknown announce type: ${object.type}`); logger.warn(`Unknown announce type: ${object.type}`);
break; break;
} }
}; };

View File

@ -1,13 +1,12 @@
import * as debug from 'debug';
import Resolver from '../../resolver'; import Resolver from '../../resolver';
import post from '../../../../services/note/create'; import post from '../../../../services/note/create';
import { IRemoteUser, IUser } from '../../../../models/user'; import { IRemoteUser, IUser } from '../../../../models/user';
import { IAnnounce, INote } from '../../type'; import { IAnnounce, INote } from '../../type';
import { fetchNote, resolveNote } from '../../models/note'; import { fetchNote, resolveNote } from '../../models/note';
import { resolvePerson } from '../../models/person'; import { resolvePerson } from '../../models/person';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
/** /**
* *
@ -32,7 +31,7 @@ export default async function(resolver: Resolver, actor: IRemoteUser, activity:
const renote = await resolveNote(note); const renote = await resolveNote(note);
log(`Creating the (Re)Note: ${uri}`); logger.info(`Creating the (Re)Note: ${uri}`);
//#region Visibility //#region Visibility
const visibility = getVisibility(activity.to, activity.cc, actor); const visibility = getVisibility(activity.to, activity.cc, actor);

View File

@ -1,18 +1,18 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import User, { IRemoteUser } from '../../../../models/user'; import User, { IRemoteUser } from '../../../../models/user';
import config from '../../../../config'; import config from '../../../../config';
import * as debug from 'debug';
import { IBlock } from '../../type'; import { IBlock } from '../../type';
import block from '../../../../services/blocking/create'; import block from '../../../../services/blocking/create';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
export default async (actor: IRemoteUser, activity: IBlock): Promise<void> => { export default async (actor: IRemoteUser, activity: IBlock): Promise<void> => {
const id = typeof activity.object == 'string' ? activity.object : activity.object.id; const id = typeof activity.object == 'string' ? activity.object : activity.object.id;
const uri = activity.id || activity; const uri = activity.id || activity;
log(`Block: ${uri}`); logger.info(`Block: ${uri}`);
if (!id.startsWith(config.url + '/')) { if (!id.startsWith(config.url + '/')) {
return null; return null;

View File

@ -1,17 +1,16 @@
import * as debug from 'debug';
import Resolver from '../../resolver'; import Resolver from '../../resolver';
import { IRemoteUser } from '../../../../models/user'; import { IRemoteUser } from '../../../../models/user';
import createNote from './note'; import createNote from './note';
import createImage from './image'; import createImage from './image';
import { ICreate } from '../../type'; import { ICreate } from '../../type';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
export default async (actor: IRemoteUser, activity: ICreate): Promise<void> => { export default async (actor: IRemoteUser, activity: ICreate): Promise<void> => {
const uri = activity.id || activity; const uri = activity.id || activity;
log(`Create: ${uri}`); logger.info(`Create: ${uri}`);
const resolver = new Resolver(); const resolver = new Resolver();
@ -20,7 +19,7 @@ export default async (actor: IRemoteUser, activity: ICreate): Promise<void> => {
try { try {
object = await resolver.resolve(activity.object); object = await resolver.resolve(activity.object);
} catch (e) { } catch (e) {
log(`Resolution failed: ${e}`); logger.error(`Resolution failed: ${e}`);
throw e; throw e;
} }
@ -34,7 +33,7 @@ export default async (actor: IRemoteUser, activity: ICreate): Promise<void> => {
break; break;
default: default:
console.warn(`Unknown type: ${object.type}`); logger.warn(`Unknown type: ${object.type}`);
break; break;
} }
}; };

View File

@ -3,6 +3,7 @@ import deleteNote from './note';
import Note from '../../../../models/note'; import Note from '../../../../models/note';
import { IRemoteUser } from '../../../../models/user'; import { IRemoteUser } from '../../../../models/user';
import { IDelete } from '../../type'; import { IDelete } from '../../type';
import { apLogger } from '../../logger';
/** /**
* *
@ -31,7 +32,7 @@ export default async (actor: IRemoteUser, activity: IDelete): Promise<void> => {
break; break;
default: default:
console.warn(`Unknown type: ${object.type}`); apLogger.warn(`Unknown type: ${object.type}`);
break; break;
} }
}; };

View File

@ -1,13 +1,12 @@
import * as debug from 'debug';
import Note from '../../../../models/note'; import Note from '../../../../models/note';
import { IRemoteUser } from '../../../../models/user'; import { IRemoteUser } from '../../../../models/user';
import deleteNode from '../../../../services/note/delete'; import deleteNode from '../../../../services/note/delete';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
export default async function(actor: IRemoteUser, uri: string): Promise<void> { export default async function(actor: IRemoteUser, uri: string): Promise<void> {
log(`Deleting the Note: ${uri}`); logger.info(`Deleting the Note: ${uri}`);
const note = await Note.findOne({ uri }); const note = await Note.findOne({ uri });

View File

@ -11,6 +11,7 @@ import reject from './reject';
import add from './add'; import add from './add';
import remove from './remove'; import remove from './remove';
import block from './block'; import block from './block';
import { apLogger } from '../logger';
const self = async (actor: IRemoteUser, activity: Object): Promise<void> => { const self = async (actor: IRemoteUser, activity: Object): Promise<void> => {
switch (activity.type) { switch (activity.type) {
@ -35,11 +36,11 @@ const self = async (actor: IRemoteUser, activity: Object): Promise<void> => {
break; break;
case 'Add': case 'Add':
await add(actor, activity).catch(err => console.log(err)); await add(actor, activity).catch(err => apLogger.error(err));
break; break;
case 'Remove': case 'Remove':
await remove(actor, activity).catch(err => console.log(err)); await remove(actor, activity).catch(err => apLogger.error(err));
break; break;
case 'Announce': case 'Announce':
@ -64,7 +65,7 @@ const self = async (actor: IRemoteUser, activity: Object): Promise<void> => {
break; break;
default: default:
console.warn(`unknown activity type: ${(activity as any).type}`); apLogger.warn(`unknown activity type: ${(activity as any).type}`);
return null; return null;
} }
}; };

View File

@ -1,16 +1,15 @@
import * as debug from 'debug';
import Resolver from '../../resolver'; import Resolver from '../../resolver';
import { IRemoteUser } from '../../../../models/user'; import { IRemoteUser } from '../../../../models/user';
import rejectFollow from './follow'; import rejectFollow from './follow';
import { IReject, IFollow } from '../../type'; import { IReject, IFollow } from '../../type';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
export default async (actor: IRemoteUser, activity: IReject): Promise<void> => { export default async (actor: IRemoteUser, activity: IReject): Promise<void> => {
const uri = activity.id || activity; const uri = activity.id || activity;
log(`Reject: ${uri}`); logger.info(`Reject: ${uri}`);
const resolver = new Resolver(); const resolver = new Resolver();
@ -19,7 +18,7 @@ export default async (actor: IRemoteUser, activity: IReject): Promise<void> => {
try { try {
object = await resolver.resolve(activity.object); object = await resolver.resolve(activity.object);
} catch (e) { } catch (e) {
log(`Resolution failed: ${e}`); logger.error(`Resolution failed: ${e}`);
throw e; throw e;
} }
@ -29,7 +28,7 @@ export default async (actor: IRemoteUser, activity: IReject): Promise<void> => {
break; break;
default: default:
console.warn(`Unknown reject type: ${object.type}`); logger.warn(`Unknown reject type: ${object.type}`);
break; break;
} }
}; };

View File

@ -1,18 +1,18 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import User, { IRemoteUser } from '../../../../models/user'; import User, { IRemoteUser } from '../../../../models/user';
import config from '../../../../config'; import config from '../../../../config';
import * as debug from 'debug';
import { IBlock } from '../../type'; import { IBlock } from '../../type';
import unblock from '../../../../services/blocking/delete'; import unblock from '../../../../services/blocking/delete';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
export default async (actor: IRemoteUser, activity: IBlock): Promise<void> => { export default async (actor: IRemoteUser, activity: IBlock): Promise<void> => {
const id = typeof activity.object == 'string' ? activity.object : activity.object.id; const id = typeof activity.object == 'string' ? activity.object : activity.object.id;
const uri = activity.id || activity; const uri = activity.id || activity;
log(`UnBlock: ${uri}`); logger.info(`UnBlock: ${uri}`);
if (!id.startsWith(config.url + '/')) { if (!id.startsWith(config.url + '/')) {
return null; return null;

View File

@ -1,13 +1,12 @@
import * as debug from 'debug';
import { IRemoteUser } from '../../../../models/user'; import { IRemoteUser } from '../../../../models/user';
import { IUndo, IFollow, IBlock, ILike } from '../../type'; import { IUndo, IFollow, IBlock, ILike } from '../../type';
import unfollow from './follow'; import unfollow from './follow';
import unblock from './block'; import unblock from './block';
import undoLike from './like'; import undoLike from './like';
import Resolver from '../../resolver'; import Resolver from '../../resolver';
import { apLogger } from '../../logger';
const log = debug('misskey:activitypub'); const logger = apLogger;
export default async (actor: IRemoteUser, activity: IUndo): Promise<void> => { export default async (actor: IRemoteUser, activity: IUndo): Promise<void> => {
if ('actor' in activity && actor.uri !== activity.actor) { if ('actor' in activity && actor.uri !== activity.actor) {
@ -16,7 +15,7 @@ export default async (actor: IRemoteUser, activity: IUndo): Promise<void> => {
const uri = activity.id || activity; const uri = activity.id || activity;
log(`Undo: ${uri}`); logger.info(`Undo: ${uri}`);
const resolver = new Resolver(); const resolver = new Resolver();
@ -25,7 +24,7 @@ export default async (actor: IRemoteUser, activity: IUndo): Promise<void> => {
try { try {
object = await resolver.resolve(activity.object); object = await resolver.resolve(activity.object);
} catch (e) { } catch (e) {
log(`Resolution failed: ${e}`); logger.error(`Resolution failed: ${e}`);
throw e; throw e;
} }

View File

@ -3,6 +3,7 @@ import $ from 'cafy'; import ID, { transform } from '../../../../../misc/cafy-id
import { validateFileName, pack } from '../../../../../models/drive-file'; import { validateFileName, pack } from '../../../../../models/drive-file';
import create from '../../../../../services/drive/add-file'; import create from '../../../../../services/drive/add-file';
import define from '../../../define'; import define from '../../../define';
import { apiLogger } from '../../../logger';
export const meta = { export const meta = {
desc: { desc: {
@ -76,7 +77,7 @@ export default define(meta, (ps, user, app, file, cleanup) => new Promise(async
res(pack(driveFile, { self: true })); res(pack(driveFile, { self: true }));
} catch (e) { } catch (e) {
console.error(e); apiLogger.error(e);
cleanup(); cleanup();

View File

@ -8,6 +8,7 @@ import rndstr from 'rndstr';
import config from '../../../../config'; import config from '../../../../config';
import * as ms from 'ms'; import * as ms from 'ms';
import * as bcrypt from 'bcryptjs'; import * as bcrypt from 'bcryptjs';
import { apiLogger } from '../../logger';
export const meta = { export const meta = {
requireCredential: true, requireCredential: true,
@ -91,10 +92,11 @@ export default define(meta, (ps, user) => new Promise(async (res, rej) => {
text: `To verify email, please click this link: ${link}` text: `To verify email, please click this link: ${link}`
}, (error, info) => { }, (error, info) => {
if (error) { if (error) {
return console.error(error); apiLogger.error(error);
return;
} }
console.log('Message sent: %s', info.messageId); apiLogger.info('Message sent: %s', info.messageId);
}); });
} }
})); }));

View File

@ -4,6 +4,7 @@ import Note from '../../../../models/note';
import { packMany } from '../../../../models/note'; import { packMany } from '../../../../models/note';
import es from '../../../../db/elasticsearch'; import es from '../../../../db/elasticsearch';
import define from '../../define'; import define from '../../define';
import { apiLogger } from '../../logger';
export const meta = { export const meta = {
desc: { desc: {
@ -52,7 +53,7 @@ export default define(meta, (ps, me) => new Promise(async (res, rej) => {
} }
}, async (error, response) => { }, async (error, response) => {
if (error) { if (error) {
console.error(error); apiLogger.error(error);
return res(500); return res(500);
} }

View File

@ -8,6 +8,7 @@ import define from '../../define';
import fetchMeta from '../../../../misc/fetch-meta'; import fetchMeta from '../../../../misc/fetch-meta';
import resolveUser from '../../../../remote/resolve-user'; import resolveUser from '../../../../remote/resolve-user';
import { getHideUserIds } from '../../common/get-hide-users'; import { getHideUserIds } from '../../common/get-hide-users';
import { apiLogger } from '../../logger';
export const meta = { export const meta = {
desc: { desc: {
@ -102,7 +103,7 @@ async function convertUsers(src: IRecommendUser[], me: ILocalUser) {
const packed = await Promise.all(src.map(async x => { const packed = await Promise.all(src.map(async x => {
const user = await resolveUser(x.username, x.host) const user = await resolveUser(x.username, x.host)
.catch(() => { .catch(() => {
console.warn(`Can't resolve ${x.username}@${x.host}`); apiLogger.warn(`Can't resolve ${x.username}@${x.host}`);
return null; return null;
}); });

View File

@ -2,6 +2,7 @@ import $ from 'cafy'; import ID, { transform, transformMany } from '../../../../
import User, { pack, isRemoteUser } from '../../../../models/user'; import User, { pack, isRemoteUser } from '../../../../models/user';
import resolveRemoteUser from '../../../../remote/resolve-user'; import resolveRemoteUser from '../../../../remote/resolve-user';
import define from '../../define'; import define from '../../define';
import { apiLogger } from '../../logger';
const cursorOption = { fields: { data: false } }; const cursorOption = { fields: { data: false } };
@ -59,7 +60,7 @@ export default define(meta, (ps, me) => new Promise(async (res, rej) => {
try { try {
user = await resolveRemoteUser(ps.username, ps.host, cursorOption); user = await resolveRemoteUser(ps.username, ps.host, cursorOption);
} catch (e) { } catch (e) {
console.warn(`failed to resolve remote user: ${e}`); apiLogger.warn(`failed to resolve remote user: ${e}`);
return rej('failed to resolve remote user'); return rej('failed to resolve remote user');
} }
} else { } else {

3
src/server/api/logger.ts Normal file
View File

@ -0,0 +1,3 @@
import Logger from "../../misc/logger";
export const apiLogger = new Logger('api');

View File

@ -4,11 +4,12 @@ import * as mongodb from 'mongodb';
import DriveFile, { getDriveFileBucket } from '../../models/drive-file'; import DriveFile, { getDriveFileBucket } from '../../models/drive-file';
import DriveFileThumbnail, { getDriveFileThumbnailBucket } from '../../models/drive-file-thumbnail'; import DriveFileThumbnail, { getDriveFileThumbnailBucket } from '../../models/drive-file-thumbnail';
import DriveFileWebpublic, { getDriveFileWebpublicBucket } from '../../models/drive-file-webpublic'; import DriveFileWebpublic, { getDriveFileWebpublicBucket } from '../../models/drive-file-webpublic';
import { serverLogger } from '..';
const assets = `${__dirname}/../../server/file/assets/`; const assets = `${__dirname}/../../server/file/assets/`;
const commonReadableHandlerGenerator = (ctx: Koa.BaseContext) => (e: Error): void => { const commonReadableHandlerGenerator = (ctx: Koa.BaseContext) => (e: Error): void => {
console.error(e); serverLogger.error(e);
ctx.status = 500; ctx.status = 500;
}; };

View File

@ -24,7 +24,7 @@ import { sum } from '../prelude/array';
import User from '../models/user'; import User from '../models/user';
import Logger from '../misc/logger'; import Logger from '../misc/logger';
const logger = new Logger('server', 'gray'); export const serverLogger = new Logger('server', 'gray');
// Init app // Init app
const app = new Koa(); const app = new Koa();
@ -33,7 +33,7 @@ app.proxy = true;
if (!['production', 'test'].includes(process.env.NODE_ENV)) { if (!['production', 'test'].includes(process.env.NODE_ENV)) {
// Logger // Logger
app.use(koaLogger(str => { app.use(koaLogger(str => {
logger.info(str); serverLogger.info(str);
})); }));
// Delay // Delay

View File

@ -4,6 +4,9 @@ import { renderActivity } from '../../remote/activitypub/renderer';
import renderBlock from '../../remote/activitypub/renderer/block'; import renderBlock from '../../remote/activitypub/renderer/block';
import renderUndo from '../../remote/activitypub/renderer/undo'; import renderUndo from '../../remote/activitypub/renderer/undo';
import { deliver } from '../../queue'; import { deliver } from '../../queue';
import Logger from '../../misc/logger';
const logger = new Logger('blocking/delete');
export default async function(blocker: IUser, blockee: IUser) { export default async function(blocker: IUser, blockee: IUser) {
const blocking = await Blocking.findOne({ const blocking = await Blocking.findOne({
@ -12,7 +15,7 @@ export default async function(blocker: IUser, blockee: IUser) {
}); });
if (blocking == null) { if (blocking == null) {
console.warn('ブロック解除がリクエストされましたがブロックしていませんでした'); logger.warn('ブロック解除がリクエストされましたがブロックしていませんでした');
return; return;
} }

View File

@ -6,6 +6,9 @@ import renderFollow from '../../remote/activitypub/renderer/follow';
import renderUndo from '../../remote/activitypub/renderer/undo'; import renderUndo from '../../remote/activitypub/renderer/undo';
import { deliver } from '../../queue'; import { deliver } from '../../queue';
import perUserFollowingChart from '../../chart/per-user-following'; import perUserFollowingChart from '../../chart/per-user-following';
import Logger from '../../misc/logger';
const logger = new Logger('following/delete');
export default async function(follower: IUser, followee: IUser) { export default async function(follower: IUser, followee: IUser) {
const following = await Following.findOne({ const following = await Following.findOne({
@ -14,7 +17,7 @@ export default async function(follower: IUser, followee: IUser) {
}); });
if (following == null) { if (following == null) {
console.warn('フォロー解除がリクエストされましたがフォローしていませんでした'); logger.warn('フォロー解除がリクエストされましたがフォローしていませんでした');
return; return;
} }

View File

@ -7,6 +7,9 @@ import { deliver } from '../../../queue';
import Following from '../../../models/following'; import Following from '../../../models/following';
import { publishMainStream } from '../../../stream'; import { publishMainStream } from '../../../stream';
import perUserFollowingChart from '../../../chart/per-user-following'; import perUserFollowingChart from '../../../chart/per-user-following';
import Logger from '../../../misc/logger';
const logger = new Logger('following/requests/accept');
export default async function(followee: IUser, follower: IUser) { export default async function(followee: IUser, follower: IUser) {
let incremented = 1; let incremented = 1;
@ -29,7 +32,7 @@ export default async function(followee: IUser, follower: IUser) {
} }
}).catch(e => { }).catch(e => {
if (e.code === 11000 && isRemoteUser(follower) && isLocalUser(followee)) { if (e.code === 11000 && isRemoteUser(follower) && isLocalUser(followee)) {
console.log(`Accept => Insert duplicated ignore. ${follower._id} => ${followee._id}`); logger.info(`Accept => Insert duplicated ignore. ${follower._id} => ${followee._id}`);
incremented = 0; incremented = 0;
} else { } else {
throw e; throw e;

View File

@ -495,7 +495,6 @@ async function insertNote(user: IUser, data: Option, tags: string[], emojis: str
return null; return null;
} }
console.error(e);
throw 'something happened'; throw 'something happened';
} }
} }

View File

@ -30,7 +30,6 @@ export default async (user: IUser, note: INote, reaction: string) => new Promise
return rej('already reacted'); return rej('already reacted');
} }
console.error(e);
return rej('something happened'); return rej('something happened');
} }