Python Logging: loguru vs logging
James Reed
Infrastructure Engineer · Leapcell

Python Logging Libraries Comparison: logging vs loguru
1. Loguru Simplifies Logging
Python開発において、ログ記録は非常に重要なツールです。開発者はプログラムの実行ステータスを記録し、問題をデバッグし、システムのヘルス状態を監視できます。Pythonには、組み込みのlogging
ライブラリがあります。しかし、要件の変化に伴い、多くの人々がloguru
を代替として使用し始めています。この記事では、これら2つのライブラリを比較して、より適切なログ記録ソリューションを選択できるようにします。
Loguru
は、人気のあるサードパーティのログ記録ライブラリです。設定プロセスを簡素化し、チェーンされた呼び出しをサポートし、より豊富な機能を提供することにより、logging
の強力な代替となっています。
Advantages of Loguru
- Simple Configuration:
Loguru
は、複雑な構成を作成する必要はありません。わずか数行のコードで複雑なログ構成を完了できます。 - Chained Calls: チェーンされた呼び出しをサポートしており、ロギングをより直感的にします。
- Multi - target Output: コンソールとファイルの両方へのログ出力を簡単に実現でき、豊富な形式構成もサポートしています。
- Extra Features: 自動ログ圧縮、ログファイルローテーション、ログ保持日数などの機能をサポートしています。
Basic Example of Loguru
from loguru import logger # Configure logging logger.add("app.log", rotation="500 MB") # The file will rotate automatically when it exceeds 500 MB # Log messages logger.info("This is an info message.") logger.warning("This is a warning message.") logger.error("This is an error message.")
この例では、複数のハンドラーを追加で構成する必要はありません。logger.add()
を呼び出すだけで、ファイルロギングの構成を簡単に完了できます。
Output to Both File and Console
Loguru
は、ファイルとコンソールの両方への出力を非常に便利に実現できます。
from loguru import logger import sys # Add logging output to file and console logger.add("app.log", rotation="500 MB", retention="10 days") # File rotation and retention for 10 days logger.add(sys.stdout, level="INFO") # Output to the console # Log messages logger.info("This is an info message.") logger.warning("This is a warning message.") logger.error("This is an error message.")
ここで、logger.add(sys.stdout, level="INFO")
を使用すると、追加の構成なしでコンソールにログを表示できます。
2. Advantages and Disadvantages of Python's Built - in logging
Advantages
- Part of the Standard Library:
logging
はPython標準ライブラリの一部であるため、追加のインストールは不要で、クロスプラットフォームです。 - Highly Customizable:
logging
は強力なカスタマイズ機能を提供し、ログ形式、レベル、およびターゲット(ファイル、コンソール、リモートサーバーなど)を柔軟に制御できます。 - Strong Compatibility: 多くのサードパーティライブラリも
logging
を使用しており、さまざまなログのシームレスな統合が可能です。
Disadvantages
- Complex Configuration:
logging
の基本的な使用は比較的簡単ですが、少し複雑な構成は冗長で直感的ではなくなります。特に、複数のターゲット(ファイルやコンソールなど)に同時に出力する必要がある場合です。 - No Chained Calls:
logging
はloguru
のようなチェーンされた呼び出しをサポートしておらず、レイヤーごとの構成が必要です。
Basic Example
logging
の簡単なログ記録の例を次に示します。
import logging # Configure logging logging.basicConfig( level = logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', filename='app.log', filemode='a' ) # Log messages logging.info("This is an info message.") logging.warning("This is a warning message.") logging.error("This is an error message.")
この例では、ログはapp.log
ファイルに記録されますが、コンソールには表示されません。コンソールとファイルの両方にログを表示する場合は、StreamHandler
を追加で構成する必要があります。
Configuration for Output to File and Console
ログをコンソールとファイルの両方に出力するには、複数のHandler
を構成する必要があります。コードは次のとおりです。
import logging # Get the logger logger = logging.getLogger() logger.setLevel(logging.INFO) # File handler file_handler = logging.FileHandler('app.log') file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')) # Console handler console_handler = logging.StreamHandler() console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')) # Add handlers to the logger logger.addHandler(file_handler) logger.addHandler(console_handler) # Log messages logger.info("This is an info message.") logger.warning("This is a warning message.") logger.error("This is an error message.")
比較的単純な機能を実現するには、異なるHandler
を作成し、それらを1つずつ構成する必要があることがわかります。
3. Detailed Comparison between logging and loguru
Feature | logging | loguru |
---|---|---|
Configuration Complexity | High, need to set Handlers | Low, only need logger.add() |
File Rotation and Retention | Need third - party module support | Built - in support for rotation and retention |
Output to Console and File Simultaneously | Need to set multiple Handlers | Easily achieved using sys.stdout |
Chained Calls | Not supported | Supported |
Ease of Use | Suitable for complex configurations and integrations | Suitable for rapid development and clear log management |
4. Recommended Application Scenarios
- Simple Applications and Rapid Development:
Loguru
is a better choice. It is concise and intuitive, suitable for rapid prototyping and small projects. - Complex Applications and Multi - module Projects: The highly customizable features provided by
logging
are more suitable for complex systems that require multi - level configurations, especially those projects that rely on third - party libraries and hope to unify log management.
5. Summary
Both loguru
and logging
have their advantages and disadvantages. For most Python projects, the concise syntax and powerful features of loguru
make it the first choice for rapid development. For larger projects, the compatibility and flexibility of the standard library logging
are more suitable. I hope this article can help you choose the appropriate logging tool for your project.
Leapcell: The Best Serverless Platform for Web Hosting
Finally, I would like to recommend the best platform for deploying Python apps: Leapcell
1. Multi - Language Support
- Develop with JavaScript, Python, Go, or Rust.
2. Deploy unlimited projects for free
- Pay only for usage — no requests, no charges.
3. Unbeatable Cost Efficiency
- Pay - as - you - go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
4. Streamlined Developer Experience
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real - time metrics and logging for actionable insights.
5. Effortless Scalability and High Performance
- Auto - scaling to handle high concurrency with ease.
- Zero operational overhead — just focus on building.
Explore more in the documentation!
Leapcell Twitter: https://x.com/LeapcellHQ