Claude Usage Logger in Python: A Step-by-Step Guide

2 min read

I recently came across the Dev.to article "Anthropic Cost Tracking: Build a Claude Usage Logger in Python" and was impressed by the simplicity and effectiveness of the solution. As an AI engineer, I wanted to dive deeper into the topic and provide a step-by-step guide on how to build a Claude usage logger in Python.

The article by Hammad Malik provides a basic framework for building a usage logger using Python. However, I wanted to take it a step further and provide a more comprehensive guide that includes additional features and best practices.

To get started, you'll need to have Python installed on your system. I'll be using Python 3.9 for this guide.

python
# Install the required libraries
pip install pandas matplotlib

The first step is to create a new Python script and import the necessary libraries. We'll be using the pandas library to handle data manipulation and the matplotlib library to create visualizations.

python
import pandas as pd
import matplotlib.pyplot as plt

Next, we need to define a function that will be responsible for logging the usage of the Claude model. This function will take in the usage data as a dictionary and write it to a CSV file.

python
def log_usage(usage_data):
    # Create a pandas DataFrame from the usage data
    df = pd.DataFrame(usage_data)
    
    # Write the DataFrame to a CSV file
    df.to_csv('usage_log.csv', index=False)

Now that we have the logging function in place, we can start collecting usage data. We'll create a new function that will be responsible for collecting the usage data.

python
def collect_usage():
    # Define the usage data as a dictionary
    usage_data = {
        'date': ['2024-01-01', '2024-01-02', '2024-01-03'],
        'requests': [100, 200, 300],
        'cost': [10.0, 20.0, 30.0]
    }
    
    # Call the log_usage function with the usage data
    log_usage(usage_data)

Finally, we can call the collect_usage function to start collecting and logging the usage data.

bash
# Run the collect_usage function
python -c "import usage_logger; usage_logger.collect_usage()"

This will create a new CSV file called usage_log.csv that contains the collected usage data.

Usage Log
2024-01-01100requests2024-01-02200requests2024-01-03300requests
Data from the sources listed below.

The usage log file will contain the following data:

daterequestscost
2024-01-0110010.0
2024-01-0220020.0
2024-01-0330030.0

This is a basic example of how to build a Claude usage logger in Python. You can customize the logging function to fit your specific needs and add additional features such as data visualization and alerting.

Try this

  • Install the required libraries by running pip install pandas matplotlib
  • Run the collect_usage function by running python -c "import usage_logger; usage_logger.collect_usage()"
  • View the usage log file by opening usage_log.csv in a spreadsheet program

Sources