{"id":22771522,"url":"https://github.com/nivisi/contextual_logging","last_synced_at":"2025-04-15T05:30:00.208Z","repository":{"id":64834773,"uuid":"578659429","full_name":"nivisi/contextual_logging","owner":"nivisi","description":"✏️ A mixin for Dart classes that brings contextual logging functionality.","archived":false,"fork":false,"pushed_at":"2022-12-16T13:34:23.000Z","size":16,"stargazers_count":8,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"develop","last_synced_at":"2025-03-28T16:21:22.405Z","etag":null,"topics":["context","contextual","dart","dartlang","flutter","library","log","logger","logging","logging-library","package","plugin","pub","pubdev"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/contextual_logging","language":"Dart","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/nivisi.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-12-15T15:21:01.000Z","updated_at":"2024-09-03T06:42:24.000Z","dependencies_parsed_at":"2023-01-29T14:00:53.802Z","dependency_job_id":null,"html_url":"https://github.com/nivisi/contextual_logging","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fcontextual_logging","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fcontextual_logging/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fcontextual_logging/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fcontextual_logging/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nivisi","download_url":"https://codeload.github.com/nivisi/contextual_logging/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249014255,"owners_count":21198553,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["context","contextual","dart","dartlang","flutter","library","log","logger","logging","logging-library","package","plugin","pub","pubdev"],"created_at":"2024-12-11T16:14:06.546Z","updated_at":"2025-04-15T05:30:00.188Z","avatar_url":"https://github.com/nivisi.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"# contextual_logging [![pub version][pub-version-img]][pub-version-url]\n\n✏️ A mixin for Dart classes that brings contextual logging functionality to your class.\n\nPrint messages like this w/o any effort.\n\n```\n10:03:00 [I] MyController : Initializing ...\n10:03:01 [I] MyController : Initialized!\n```\n\n\u003e 🌐 Is built on top of the [`logger`](https://pub.dev/packages/logger) package.\n\n### Table of contents\n\n- [What's contextual logging?](#whats-contextual-logging)\n- [Logger](#logger)\n  - [The mixin](#the-mixin)\n  - [Configuration](#configuration)\n    - [Context](#context)\n    - [Custom logger](#custom-logger)\n  - [Default logger config everywhere](#default-logger-config-everywhere)\n- [Contextual log printer](#contextual-log-printer)\n  - [What's this?](#whats-this)\n  - [Configuring the printer](#configuring-the-printer)\n    - [Example](#example)\n    - [Log level label](#log-level-label)\n\n## What's contextual logging?\n\nWe all know log messages. They are printed to the console, to the files or whatever. Dart provides us with methods for logging like:\n\n```dart\nprint('A message');\ndebugPrint('Another message');\n```\n\nGood enough to debug. But when you actually need to investigate users' journey, it is not. You'll need context. The context here answers the question `who has printed the message?`.\n\nAdding context could be done like this:\n\n```dart\nprint('My Controller : A message');\ndebugPrint('My Controller : Another message');\n```\n\n... and it will work. Though to write the context every time is pretty boring. This is what `contextual_logging` solves.\n\n## Logger\n\n### The mixin\n\nAttach the mixin it to your class that you want to use for logging:\n\n```dart\nclass MyController with ContextualLogging\n```\n\nAnd now go for it!\n\n```dart\nclass MyController with ContextualLogging {\n  Future\u003cvoid\u003e init() async {\n    log.i('Initializing ...'); // \u003c-- Access logging via the log field\n    await fetchData();\n    log.i('Initialized!');\n  }\n}\n```\n\nYou will see this in the console:\n\n```\n10:03:00 [I] MyController : Initializing ...\n10:03:01 [I] MyController : Initialized!\n```\n\n### Configuration\n\nBy default, a logger is created for every object that has a `ContextualLogging` mixin attached to it. Once you attach the mixin, you'll be able to configure the logger for this object.\n\n#### Context\n\n`logContext` property is what Contextual Logger adds to the log message in front of the main message. By default it has a value of `this.toString()`. Override it to whatever you want:\n\n```dart\nclass MyController with ContextualLogging {\n  @override\n  String get logContext =\u003e 'SomeOtherContext`;\n  \n  void test() {\n    log.i('Test'); // 19:12:00 [I] SomeOtherContext : Test\n  }\n}\n```\n\n#### Custom logger\n\nIf you want to use a custom logger, feel free to override the `customLogger` property:\n\n```dart\nclass MyController with ContextualLogging {\n  @override\n  Logger get customLogger =\u003e Logger(/* Configure it in whatever way you want! */);\n  \n  void test() {\n    log.i('Test'); // Still access it via the `log` property!\n  }\n}\n```\n\n### Default logger config everywhere\n\nIf you want to reconfigure loggers for all the object at once, do this before your app starts:\n\n```dart\n// ContextualLogger mixin uses this defaultLogger by default to get a logger for the object it was attached to.\nContextualLoggingConfig.defaultLogger = (forObject) =\u003e MyBeautifulLogger(forObject);\n```\n\nOnce you do it, every `ContextualLogger` mixin will create loggers like this.\n\n## Contextual Log Printer\n\n\u003e 💡 A printer is what formats your messages.\n\n### What's this?\n\nWhen setting the `ContextualLoggingConfig.defaultLogger` property, you can create a logger and provide any printer you want. Or you can use the default printer used by `ContextualLogger`, the `ContextualLogPrinter`. This printer is what makes the messages look like this: \n\n```\n12:01:00 [I] SomeOtherContext : Test\n```\n\nInstead of this:\n\n```\nTest\n```\n\n### Configuring the printer\n\nThere are plenty of properties you can change:\n\n| Property      | Type       | Description                                  | Default      |\n| :------------ | :--------- | :------------------------------------------- | :----------- |\n| forObject     | Object     | The object for which the logger was created. Use a `string` if you want to have it as a prefix. | this |\n| timeFormat    | DateFormat | Format of the current timestamp              | HH:mm:ss     |\n| timeInUtc     | bool       | Whether the current timestamp must be in UTC | false        |\n| printTime     | bool       | Whether to print the timestamp               | true         |\n| logLevelLabel | Function   | Log level prefix for messages                | [I], [W] etc |\n\n#### Example\n\nSo imagine you've overridden the printer like this:\n\n```dart\nContextualLoggingConfig.defaultLogger = (forObject) {\n  return Logger(\n    printer: ContextualLogPrinter(\n      forObject: forObject,\n      printTime: false, // Note!\n    ),\n  );\n};\n\n// This will make your messages look like this:\n\n[I] MyController : A message\n```\n\n#### Log level label\n\nLog level lebel is what allows you to distinguish the level of a message. The [`logger`](https://pub.dev/packages/logger) package allows you to use these levels:\n\n| Level   | Function                      | Default | Emoji  |\n| :------ | :---------------------------- | :------ | :----  |\n| Verbose | `log.v`                       | [V]     | *None* |\n| Debug   | `log.d`                       | [D]     | 🐛     |\n| Info    | `log.i`                       | [I]     | 💡     |\n| Warning | `log.w`                       | [W]     | ⚠️     |\n| Error   | `log.e`                       | [E]     | ⛔️     |\n| Wtf     | `log.wtf`                     | [WTF]   | 🗿     |\n| Nothing | `log.log(Level.nothing, ...)` | *None*  | *None* |\n\nOverride the `logLevelLabel` property to make your own prefixes!\n\n```dart\nContextualLoggingConfig.defaultLogger = (forObject) {\n  return Logger(\n    printer: ContextualLogPrinter(\n      forObject: forObject,\n      logLevelLabel: (level) {\n        /* Return a prefix for the given level! */\n      },\n    ),\n  );\n  \n// Or do this to enable emojis level!\nContextualLoggingConfig.defaultLogger = (forObject) {\n  return Logger(\n    printer: ContextualLogPrinter(\n      forObject: forObject,\n      logLevelLabel: ContextualLogPrinter.emojiLevelLabel,\n    ),\n  );\n```\n\n\u003c!-- References --\u003e\n[pub-version-img]: https://img.shields.io/badge/pub-v1.0.2+1-0175c2?logo=dart\n[pub-version-url]: https://pub.dev/packages/contextual_logging","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnivisi%2Fcontextual_logging","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnivisi%2Fcontextual_logging","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnivisi%2Fcontextual_logging/lists"}