Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

enhance:add file output of log (#1838)

Yifeng Wang(正经人王同学)b053c9dece57
diff --git a/camel/logger.py b/camel/logger.py
index 807a5b406..b901235ff 100644
--- a/camel/logger.py
+++ b/camel/logger.py
@@ -12,6 +12,7 @@
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
import logging
import os
import sys
@@ -42,9 +43,51 @@ def _configure_library_logging():
_logger.debug("Existing logger configuration found, using that.")
+def set_log_file(file_path):
+ r"""Set a file handler for the CAMEL library logging.
+
+ Args:
+ file_path (str): Path to the log file. If the directory doesn't exist,
+ it will be created.
+
+ Returns:
+ logging.FileHandler: The file handler that was added to the logger.
+ """
+ # Check for existing handlers to the same file
+ for handler in _logger.handlers:
+ if isinstance(handler, logging.FileHandler) and os.path.abspath(
+ handler.baseFilename
+ ) == os.path.abspath(file_path):
+ _logger.info(f"File handler already exists for: {file_path}")
+ return handler
+
+ # Create directory if it doesn't exist
+ log_dir = os.path.dirname(file_path)
+ if log_dir and not os.path.exists(log_dir):
+ os.makedirs(log_dir)
+
+ # Create file handler
+ file_handler = logging.FileHandler(file_path)
+ file_handler.setFormatter(
+ logging.Formatter(
+ '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+ )
+ )
+
+ # Set the same level as the logger
+ file_handler.setLevel(_logger.getEffectiveLevel())
+
+ # Add the handler to the logger
+ _logger.addHandler(file_handler)
+ _logger.info(f"Log file configured at: {file_path}")
+
+ return file_handler
+
+
def disable_logging():
r"""Disable all logging for the CAMEL library.
+
This function sets the log level to a value higher than CRITICAL,
effectively disabling all log messages, and adds a NullHandler to
suppress any potential warnings about no handlers being found.
@@ -63,6 +106,7 @@ def disable_logging():
def enable_logging():
r"""Enable logging for the CAMEL library.
+
This function re-enables logging if it was previously disabled,
and configures the library logging using the default settings.
If the logging is already configured,
@@ -75,12 +119,14 @@ def enable_logging():
def set_log_level(level):
r"""Set the logging level for the CAMEL library.
+
Args:
level (Union[str, int]): The logging level to set. This can be a string
(e.g., 'INFO') or a logging level constant (e.g., logging.INFO,
logging.DEBUG).
See https://docs.python.org/3/library/logging.html#levels
+
Raises:
ValueError: If the provided level is not a valid logging level.
"""
@@ -98,15 +144,25 @@ def set_log_level(level):
)
_logger.setLevel(level)
+
+ # Update level for all handlers
+ for handler in _logger.handlers:
+ try:
+ handler.setLevel(level)
+ except Exception as e:
+ _logger.warning(f"Failed to set level on handler {handler}: {e}")
+
_logger.debug(f"Logging level set to: {logging.getLevelName(level)}")
def get_logger(name):
r"""Get a logger with the specified name, prefixed with 'camel.'.
+
Args:
name (str): The name to be appended to 'camel.' to create the logger.
+
Returns:
logging.Logger: A logger instance with the name 'camel.{name}'.
"""
diff --git a/docs/key_modules/workforce.md b/docs/key_modules/workforce.md
index 19976937d..54ecb441d 100644
--- a/docs/key_modules/workforce.md
+++ b/docs/key_modules/workforce.md
@@ -60,7 +60,7 @@ has been failed for a certain number of times (3 by default).
Here is a diagram illustrating the workflow with a simple example.
-![Workforce Example](https://i.postimg.cc/261dDM9W/work-force.png)
+![Workforce Example](https://i.postimg.cc/jSnjsN57/Wechat-IMG1592.jpg)
## Get Started
diff --git a/examples/files_log.py b/examples/files_log.py
new file mode 100644
index 000000000..e14bf8506
--- /dev/null
+++ b/examples/files_log.py
@@ -0,0 +1,32 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import os
+
+from camel.logger import get_logger, set_log_file, set_log_level
+
+# Set log output to a file using an absolute path
+log_path = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)),
+ 'camel.log',
+)
+set_log_file(log_path)
+
+# Set the logging level
+set_log_level('DEBUG')
+
+# Use the logger
+logger = get_logger(__name__)
+logger.debug('This is a debug message')
+logger.info('This is an info message')
+logger.warning('This is a warning message')