> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# DataStore のロギング

> デバッグと監視のための DataStore のロギング設定

DataStore は Python 標準のロギングモジュールを使用します。このガイドでは、デバッグ用にロギングを設定する方法を説明します。

<div id="quick-start">
  ## クイックスタート
</div>

```python theme={null}
from pathlib import Path
Path("data.csv").write_text("""\
name,age,city,salary,department
Alice,25,NYC,55000,Engineering
Bob,30,LA,65000,Product
Charlie,35,NYC,80000,Engineering
Diana,28,SF,70000,Design
Eve,42,NYC,95000,Product
""")

from chdb import datastore as pd
from chdb.datastore.config import config

# デバッグログを有効にする
config.enable_debug()

# これ以降のすべての操作の詳細がログに記録される
ds = pd.read_csv("data.csv")
result = ds.filter(ds['age'] > 25).to_df()
```

<div id="levels">
  ## ログレベル
</div>

| レベル        | 値  | 説明              |
| ---------- | -- | --------------- |
| `DEBUG`    | 10 | デバッグ用の詳細情報      |
| `INFO`     | 20 | 一般的な運用情報        |
| `WARNING`  | 30 | 警告メッセージ (デフォルト) |
| `ERROR`    | 40 | エラーメッセージ        |
| `CRITICAL` | 50 | 重大な障害           |

<div id="setting-level">
  ## ログレベルの設定
</div>

```python theme={null}
import logging
from chdb.datastore.config import config

# 標準ログレベルを使用する
config.set_log_level(logging.DEBUG)
config.set_log_level(logging.INFO)
config.set_log_level(logging.WARNING)  # デフォルト
config.set_log_level(logging.ERROR)

# クイックプリセットを使用する
config.enable_debug()  # DEBUGレベルと詳細フォーマットを設定する
```

<div id="format">
  ## ログフォーマット
</div>

<div id="simple">
  ### シンプル フォーマット (デフォルト)
</div>

```python title="Query" theme={null}
config.set_log_format("simple")
```

```text title="Response" theme={null}
DEBUG - Executing SQL query
DEBUG - Cache miss for key abc123
```

<div id="verbose">
  ### 詳細フォーマット
</div>

```python title="Query" theme={null}
config.set_log_format("verbose")
```

```text title="Response" theme={null}
2024-01-15 10:30:45.123 DEBUG datastore.core - Executing SQL query
2024-01-15 10:30:45.456 DEBUG datastore.cache - Cache miss for key abc123
```

***

<div id="what-logged">
  ## ログに記録される内容
</div>

<div id="debug-logged">
  ### DEBUG レベル
</div>

* 生成された SQL クエリ
* 実行エンジンの選択
* cache の操作 (hits/misses)
* 各処理の所要時間
* データソースの情報

```text theme={null}
DEBUG - Creating DataStore from file 'data.csv'
DEBUG - SQL: SELECT * FROM file('data.csv', 'CSVWithNames') WHERE age > 25
DEBUG - Using engine: chdb
DEBUG - Execution time: 0.089s
DEBUG - Cache: Storing result (key: abc123)
```

<div id="info-logged">
  ### INFO レベル
</div>

* 主要な操作の完了時
* 設定変更
* データソースへの接続

```text theme={null}
INFO - Loaded 1,000,000 rows from data.csv
INFO - Execution engine set to: chdb
INFO - Connected to MySQL: localhost:3306/mydb
```

<div id="warning-logged">
  ### WARNING レベル
</div>

* 非推奨機能の使用
* パフォーマンスに関する警告
* 軽微な問題

```text theme={null}
WARNING - Large result set (>1M rows) may cause memory issues
WARNING - Cache TTL exceeded, re-executing query
WARNING - Column 'date' has mixed types, using string
```

<div id="error-logged">
  ### ERROR レベル
</div>

* クエリ実行エラー
* 接続エラー
* データ変換エラー

```text theme={null}
ERROR - Failed to execute SQL: syntax error near 'FORM'
ERROR - Connection to MySQL failed: timeout
ERROR - Cannot convert column 'price' to float
```

***

<div id="custom">
  ## カスタムロギング設定
</div>

<div id="python-logging">
  ### Pythonのロギングを使う
</div>

```python theme={null}
import logging

# ルートロガーを設定する
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('datastore.log'),
        logging.StreamHandler()
    ]
)

# DataStore ロガーを取得する
ds_logger = logging.getLogger('chdb.datastore')
ds_logger.setLevel(logging.DEBUG)
```

<div id="log-file">
  ### ログをファイルに出力
</div>

```python theme={null}
import logging

# ファイルハンドラーを作成する
file_handler = logging.FileHandler('datastore_debug.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))

# DataStore ロガーに追加する
ds_logger = logging.getLogger('chdb.datastore')
ds_logger.addHandler(file_handler)
```

<div id="suppress">
  ### ロギングを抑制
</div>

```python theme={null}
import logging

# すべてのDataStoreログを抑制する
logging.getLogger('chdb.datastore').setLevel(logging.CRITICAL)

# またはconfigを使用する
config.set_log_level(logging.CRITICAL)
```

***

<div id="scenarios">
  ## デバッグ シナリオ
</div>

<div id="debug-sql">
  ### SQL生成のデバッグ
</div>

```python theme={null}
config.enable_debug()

ds = pd.read_csv("data.csv")
result = ds.filter(ds['age'] > 25).groupby('city').sum()
```

ログ出力:

```text theme={null}
DEBUG - Creating DataStore from file 'data.csv'
DEBUG - Building filter: age > 25
DEBUG - Building groupby: city
DEBUG - Building aggregation: sum
DEBUG - Generated SQL:
        SELECT city, SUM(*) 
        FROM file('data.csv', 'CSVWithNames')
        WHERE age > 25
        GROUP BY city
```

<div id="debug-engine">
  ### エンジン選択のデバッグ
</div>

```python theme={null}
config.enable_debug()

result = ds.filter(ds['x'] > 10).apply(custom_func)
```

ログ出力:

```text theme={null}
DEBUG - filter: selecting engine (eligible: chdb, pandas)
DEBUG - filter: using chdb (SQL-compatible)
DEBUG - apply: selecting engine (eligible: pandas)
DEBUG - apply: using pandas (custom function)
```

<div id="debug-cache">
  ### cache 操作のトラブルシューティング
</div>

```python theme={null}
config.enable_debug()

# 初回実行
result1 = ds.filter(ds['age'] > 25).to_df()
# DEBUG - クエリハッシュ abc123 のcacheミス
# DEBUG - クエリを実行中...
# DEBUG - 結果をcache中 (key: abc123, size: 1.2MB)

# 2回目の実行（同一クエリ）
result2 = ds.filter(ds['age'] > 25).to_df()
# DEBUG - クエリハッシュ abc123 のcacheヒット
# DEBUG - cachedされた結果を返却中
```

<div id="debug-performance">
  ### パフォーマンス問題のデバッグ
</div>

```python theme={null}
config.enable_debug()
config.enable_profiling()

# 各操作のタイミングがログに出力されます
result = (ds
    .filter(ds['amount'] > 100)
    .groupby('region')
    .agg({'amount': 'sum'})
    .to_df()
)
```

ログ出力:

```text theme={null}
DEBUG - filter: 0.002ms
DEBUG - groupby: 0.001ms
DEBUG - agg: 0.003ms
DEBUG - SQL generation: 0.012ms
DEBUG - SQL execution: 89.456ms  <- 主な処理時間はここ
DEBUG - Result conversion: 2.345ms
```

***

<div id="production">
  ## 本番環境向け設定
</div>

<div id="recommended">
  ### 推奨設定
</div>

```python theme={null}
import logging
from chdb.datastore.config import config

# 本番環境: 最小限のログ
config.set_log_level(logging.WARNING)
config.set_log_format("simple")
config.set_profiling_enabled(False)
```

<div id="rotation">
  ### ログローテーション
</div>

```python theme={null}
import logging
from logging.handlers import RotatingFileHandler

# ローテーティングファイルハンドラーを作成する
handler = RotatingFileHandler(
    'datastore.log',
    maxBytes=10*1024*1024,  # 10MB
    backupCount=5
)
handler.setLevel(logging.WARNING)

# DataStore ロガーに追加する
logging.getLogger('chdb.datastore').addHandler(handler)
```

***

<div id="env-vars">
  ## 環境変数
</div>

環境変数を使ってロギングを設定することもできます。

```bash theme={null}
# ログレベルを設定する
export CHDB_LOG_LEVEL=DEBUG

# ログフォーマットを設定する
export CHDB_LOG_FORMAT=verbose
```

```python theme={null}
import os
import logging

# 環境変数から読み込む
log_level = os.environ.get('CHDB_LOG_LEVEL', 'WARNING')
config.set_log_level(getattr(logging, log_level))
```

***

<div id="summary">
  ## 概要
</div>

| タスク         | コマンド                                     |
| ----------- | ---------------------------------------- |
| デバッグを有効にする  | `config.enable_debug()`                  |
| ログレベルを設定    | `config.set_log_level(logging.DEBUG)`    |
| ログフォーマットを設定 | `config.set_log_format("verbose")`       |
| ファイルにログを出力  | Python の logging ハンドラーを使用                |
| ログを抑制する     | `config.set_log_level(logging.CRITICAL)` |
