{"id":19873970,"url":"https://github.com/metarhia/metalog","last_synced_at":"2026-03-10T23:10:58.015Z","repository":{"id":23645931,"uuid":"99510554","full_name":"metarhia/metalog","owner":"metarhia","description":"Metarhia logger 📝","archived":false,"fork":false,"pushed_at":"2025-10-13T23:28:38.000Z","size":767,"stargazers_count":39,"open_issues_count":3,"forks_count":15,"subscribers_count":14,"default_branch":"master","last_synced_at":"2025-10-20T18:35:17.988Z","etag":null,"topics":["api","application-server","cloud","console","hacktoberfest","highload","impress","log","logger","logging","meta-edu","metarhia","node","nodejs","server","tools"],"latest_commit_sha":null,"homepage":"https://metarhia.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/metarhia.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"patreon":"tshemsedinov"}},"created_at":"2017-08-06T20:06:09.000Z","updated_at":"2025-10-13T23:25:04.000Z","dependencies_parsed_at":"2023-10-02T20:21:36.147Z","dependency_job_id":"ebce2f84-446f-4d6e-b32a-61c341bd1c86","html_url":"https://github.com/metarhia/metalog","commit_stats":{"total_commits":180,"total_committers":16,"mean_commits":11.25,"dds":"0.18888888888888888","last_synced_commit":"614414cee6f975f813c417a147ca1b9ece77613f"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"purl":"pkg:github/metarhia/metalog","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metarhia%2Fmetalog","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metarhia%2Fmetalog/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metarhia%2Fmetalog/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metarhia%2Fmetalog/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/metarhia","download_url":"https://codeload.github.com/metarhia/metalog/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metarhia%2Fmetalog/sbom","scorecard":{"id":637934,"data":{"date":"2025-08-11","repo":{"name":"github.com/metarhia/metalog","commit":"53e4d14e17395e04fee0055639a652060cd872f0"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":4.9,"checks":[{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/test.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Maintained","score":4,"reason":"4 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 4","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Code-Review","score":1,"reason":"Found 3/25 approved changesets -- score normalized to 1","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Security-Policy","score":10,"reason":"security policy file detected","details":["Info: security policy file detected: SECURITY.md:1","Info: Found linked content: SECURITY.md:1","Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1","Info: Found text in security policy: SECURITY.md:1"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Pinned-Dependencies","score":2,"reason":"dependency not pinned by hash detected -- score normalized to 2","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/metarhia/metalog/test.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/metarhia/metalog/test.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/metarhia/metalog/test.yml/master?enable=pin","Info:   0 out of   3 GitHub-owned GitHubAction dependencies pinned","Info:   1 out of   1 npmCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 11 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":8,"reason":"2 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-xffm-g5w8-qvg7","Warn: Project is vulnerable to: GHSA-v6h2-p8h4-qcjw"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-21T09:48:09.019Z","repository_id":23645931,"created_at":"2025-08-21T09:48:09.019Z","updated_at":"2025-08-21T09:48:09.019Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30361037,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-10T21:41:54.280Z","status":"ssl_error","status_checked_at":"2026-03-10T21:40:59.357Z","response_time":106,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","application-server","cloud","console","hacktoberfest","highload","impress","log","logger","logging","meta-edu","metarhia","node","nodejs","server","tools"],"created_at":"2024-11-12T16:20:44.665Z","updated_at":"2026-03-10T23:10:58.010Z","avatar_url":"https://github.com/metarhia.png","language":"JavaScript","funding_links":["https://patreon.com/tshemsedinov"],"categories":[],"sub_categories":[],"readme":"# Meta Logger for Metarhia\n\n[![ci status](https://github.com/metarhia/metalog/workflows/Testing%20CI/badge.svg)](https://github.com/metarhia/metalog/actions?query=workflow%3A%22Testing+CI%22+branch%3Amaster)\n[![snyk](https://snyk.io/test/github/metarhia/impress/badge.svg)](https://snyk.io/test/github/metarhia/impress)\n[![npm version](https://img.shields.io/npm/v/metalog.svg?style=flat)](https://www.npmjs.com/package/metalog)\n[![npm downloads/month](https://img.shields.io/npm/dm/metalog.svg)](https://www.npmjs.com/package/metalog)\n[![npm downloads](https://img.shields.io/npm/dt/metalog.svg)](https://www.npmjs.com/package/metalog)\n[![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/metarhia/metalog/blob/master/LICENSE)\n\n## Output example\n\n\u003cimg src=\"https://user-images.githubusercontent.com/4405297/111154959-7b99c700-859c-11eb-81bb-0f8398535106.png\" width=\"60%\"/\u003e\n\n## Usage\n\n```js\nconst logger = await Logger.create({\n  path: './log', // absolute or relative path\n  workerId: 7, // mark for process or thread\n  flushInterval: 3000, // flush log to disk interval (default: 3s)\n  writeBuffer: 64 * 1024, // buffer size (default: 64kb)\n  keepDays: 5, // delete after N days, 0 - disable (default: 1)\n  home: process.cwd(), // remove substring from paths\n  json: false, // print logs in JSON format (default: false)\n  toFile: ['log', 'info', 'warn', 'error'], // tags to write to file (default: all)\n  toStdout: ['log', 'info', 'warn', 'error'], // tags to write to stdout (default: all)\n  createStream: () =\u003e fs.createWriteStream, // custom stream factory (optional)\n  crash: 'flush', // crash handling: 'flush' to flush buffer on exit (optional)\n});\n\nconst { console } = logger;\n\nconsole.log('Test message');\nconsole.info('Info message');\nconsole.warn('Warning message');\nconsole.error('Error message');\nconsole.debug('Debug message');\n\nconsole.assert(true, 'Assertion passed');\nconsole.assert(false, 'Assertion failed');\nconsole.count('counter');\nconsole.count('counter');\nconsole.countReset('counter');\n\nconsole.time('operation');\n// ... some operation ...\nconsole.timeEnd('operation');\nconsole.timeLog('operation', 'Checkpoint');\n\nconsole.group('Group 1');\nconsole.log('Nested message');\nconsole.groupCollapsed('Group 2');\nconsole.log('Collapsed group message');\nconsole.groupEnd();\nconsole.groupEnd();\n\nconsole.dir({ key: 'value' });\nconsole.dirxml('\u003cdiv\u003eHTML content\u003c/div\u003e');\nconsole.table([\n  { name: 'John', age: 30 },\n  { name: 'Jane', age: 25 },\n]);\n\nconsole.trace('Trace message');\n\nawait logger.close();\n```\n\n## Console API Compatibility\n\nMetalog provides a fully compatible console implementation that supports all Node.js console methods:\n\n- `console.log([data][, ...args])` - General logging\n- `console.info([data][, ...args])` - Informational messages\n- `console.warn([data][, ...args])` - Warning messages\n- `console.error([data][, ...args])` - Error messages\n- `console.debug([data][, ...args])` - Debug messages\n- `console.assert(value[, ...message])` - Assertion testing\n- `console.clear()` - Clear the console\n- `console.count([label])` - Count occurrences\n- `console.countReset([label])` - Reset counter\n- `console.dir(obj[, options])` - Object inspection\n- `console.dirxml(...data)` - XML/HTML inspection\n- `console.group([...label])` - Start group\n- `console.groupCollapsed()` - Start collapsed group\n- `console.groupEnd()` - End group\n- `console.table(tabularData[, properties])` - Table display\n- `console.time([label])` - Start timer\n- `console.timeEnd([label])` - End timer\n- `console.timeLog([label][, ...data])` - Log timer value\n- `console.trace([message][, ...args])` - Stack trace\n\nAll methods maintain the same behavior as Node.js native console, with output routed through the metalog system for consistent formatting and file logging.\n\n## Configuration Options\n\n### LoggerOptions\n\n| Option          | Type       | Default                                     | Description                                         |\n| --------------- | ---------- | ------------------------------------------- | --------------------------------------------------- |\n| `path`          | `string`   | **required**                                | Directory path for log files (absolute or relative) |\n| `home`          | `string`   | **required**                                | Base path to remove from stack traces               |\n| `workerId`      | `number`   | `undefined`                                 | Worker/process identifier (appears as W0, W1, etc.) |\n| `flushInterval` | `number`   | `3000`                                      | Flush buffer to disk interval in milliseconds       |\n| `writeBuffer`   | `number`   | `65536`                                     | Buffer size threshold before flushing (64KB)        |\n| `keepDays`      | `number`   | `1`                                         | Days to keep log files (0 = disable rotation)       |\n| `json`          | `boolean`  | `false`                                     | Output logs in JSON format                          |\n| `toFile`        | `string[]` | `['log', 'info', 'warn', 'debug', 'error']` | Log tags to write to file                           |\n| `toStdout`      | `string[]` | `['log', 'info', 'warn', 'debug', 'error']` | Log tags to write to stdout                         |\n| `createStream`  | `function` | `fs.createWriteStream`                      | Custom stream factory function                      |\n| `crash`         | `string`   | `undefined`                                 | Crash handling mode ('flush' to flush on exit)      |\n\n### Log Tags\n\nMetalog supports five log tags that can be filtered independently for file and console output:\n\n- `log` - General logging\n- `info` - Informational messages\n- `warn` - Warning messages\n- `debug` - Debug messages\n- `error` - Error messages\n\n## Advanced Usage\n\n### Custom Stream Factory\n\n```js\nconst logger = await Logger.create({\n  path: './log',\n  home: process.cwd(),\n  createStream: (filePath) =\u003e {\n    // Custom compression stream\n    const fs = require('fs');\n    const zlib = require('zlib');\n    const gzip = zlib.createGzip();\n    const writeStream = fs.createWriteStream(filePath + '.gz');\n    return gzip.pipe(writeStream);\n  },\n});\n```\n\n### Selective Logging\n\n```js\n// Only log errors to file, all tags to console\nconst logger = await Logger.create({\n  path: './log',\n  home: process.cwd(),\n  toFile: ['error'],\n  toStdout: ['log', 'info', 'warn', 'debug', 'error'],\n});\n\n// Only log info and above tags to both file and console\nconst logger = await Logger.create({\n  path: './log',\n  home: process.cwd(),\n  toFile: ['info', 'warn', 'error'],\n  toStdout: ['info', 'warn', 'error'],\n});\n```\n\n### JSON Logging\n\n```js\nconst logger = await Logger.create({\n  path: './log',\n  home: process.cwd(),\n  json: true,\n});\n\nlogger.console.info('User action', { userId: 123, action: 'login' });\n// Output: {\"timestamp\":\"2025-01-07T10:30:00.000Z\",\"worker\":\"W0\",\"tag\":\"info\",\"message\":\"User action\",\"userId\":123,\"action\":\"login\"}\n```\n\n### Log Rotation and Cleanup\n\n```js\nconst logger = await Logger.create({\n  path: './log',\n  home: process.cwd(),\n  keepDays: 7, // Keep logs for 7 days\n  workerId: 1,\n});\n\n// Manual rotation\nawait logger.rotate();\n\n// Log files are automatically rotated daily\n// Old files are cleaned up based on keepDays setting\n```\n\n### Error Handling\n\n```js\nconst logger = await Logger.create({\n  path: './log',\n  home: process.cwd(),\n  crash: 'flush', // Flush buffer on process exit\n});\n\nlogger.on('error', (error) =\u003e {\n  console.error('Logger error:', error.message);\n});\n\n// Graceful shutdown\nprocess.on('SIGTERM', async () =\u003e {\n  await logger.close();\n  process.exit(0);\n});\n```\n\n## API Reference\n\n### Logger Class\n\n#### Constructor\n\n```js\nnew Logger(options: LoggerOptions): Promise\u003cLogger\u003e\n```\n\n#### Static Methods\n\n- `Logger.create(options: LoggerOptions): Promise\u003cLogger\u003e` - Create and open logger\n\n#### Instance Methods\n\n- `open(): Promise\u003cLogger\u003e` - Open log file and start logging\n- `close(): Promise\u003cvoid\u003e` - Close logger and flush remaining data\n- `rotate(): Promise\u003cvoid\u003e` - Manually trigger log rotation\n- `write(tag: string, indent: number, args: unknown[]): void` - Low-level write method\n- `flush(callback?: (error?: Error) =\u003e void): void` - Flush buffer to disk\n\n#### Properties\n\n- `active: boolean` - Whether logger is currently active\n- `path: string` - Log directory path\n- `home: string` - Home directory for path normalization\n- `console: Console` - Console instance for logging\n\n### BufferedStream Class\n\n```js\nconst stream = new BufferedStream({\n  stream: fs.createWriteStream('output.log'),\n  writeBuffer: 32 * 1024, // 32KB buffer\n  flushInterval: 5000, // 5 second flush interval\n});\n\nstream.write(Buffer.from('data'));\nstream.flush();\nawait stream.close();\n```\n\n### Formatter Class\n\n```js\nconst formatter = new Formatter({\n  worker: 'W1',\n  home: '/app',\n  json: false,\n});\n\nconst formatted = formatter.formatPretty('info', 0, ['Message']);\nconst jsonOutput = formatter.formatJson('error', 0, [error]);\n```\n\n## Best Practices\n\n### Performance Optimization\n\n1. **Buffer Size**: Adjust `writeBuffer` based on your log volume\n   - High volume: 128KB or larger\n   - Low volume: 16KB or smaller\n\n2. **Flush Interval**: Balance between performance and data safety\n   - Production: 3-10 seconds\n   - Development: 1-3 seconds\n\n3. **Selective Logging**: Use `toFile` and `toStdout` to reduce I/O\n   ```js\n   // Production: Only errors to file, warnings+ to console\n   toFile: ['error'],\n   toStdout: ['warn', 'error']\n   ```\n\n### Log Management\n\n1. **Rotation Strategy**: Set appropriate `keepDays` based on storage\n2. **Path Organization**: Use structured paths for multi-service deployments\n\n   ```js\n   path: `/var/log/app/${process.env.NODE_ENV}/${process.env.SERVICE_NAME}`;\n   ```\n\n3. **Error Handling**: Always handle logger errors\n   ```js\n   logger.on('error', (error) =\u003e {\n     // Fallback logging or alerting\n   });\n   ```\n\n### Development vs Production\n\n```js\nconst isDevelopment = process.env.NODE_ENV === 'development';\n\nconst logger = await Logger.create({\n  path: './log',\n  home: process.cwd(),\n  json: !isDevelopment, // JSON in production, pretty in dev\n  toFile: isDevelopment ? ['log', 'info', 'warn', 'error'] : ['error'],\n  toStdout: isDevelopment\n    ? ['log', 'info', 'warn', 'debug', 'error']\n    : ['warn', 'error'],\n  flushInterval: isDevelopment ? 1000 : 5000,\n  keepDays: isDevelopment ? 1 : 30,\n});\n```\n\n## Troubleshooting\n\n### Common Issues\n\n**Logs not appearing in files:**\n\n- Check `path` directory exists and is writable\n- Verify `toFile` array includes desired log tags\n- Ensure logger is properly opened with `await logger.open()`\n\n**High memory usage:**\n\n- Reduce `writeBuffer` size\n- Increase `flushInterval` frequency\n- Use selective logging with `toFile`/`toStdout`\n\n**Missing logs on crash:**\n\n- Set `crash: 'flush'` option\n- Handle process signals properly\n- Use try/catch around critical operations\n\n**Performance issues:**\n\n- Use JSON format for high-volume logging\n- Disable file logging for debug tags in production\n- Consider using separate loggers for different components\n\n### Debug Mode\n\n```js\n// Enable debug logging\nconst logger = await Logger.create({\n  path: './log',\n  home: process.cwd(),\n  toStdout: ['debug', 'info', 'warn', 'error'],\n});\n\nlogger.console.debug('Debug information', { data: 'value' });\n```\n\n## License \u0026 Contributors\n\nCopyright (c) 2017-2026 [Metarhia contributors](https://github.com/metarhia/metalog/graphs/contributors).\nMetalog is [MIT licensed](./LICENSE).\\\nMetalog is a part of [Metarhia](https://github.com/metarhia) technology stack.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmetarhia%2Fmetalog","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmetarhia%2Fmetalog","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmetarhia%2Fmetalog/lists"}