![](/img/trans.png)
[英]Writing custom log files in Databricks Repos using the logging package
[英]Writing log with python logging module in databricks to azure datalake not working
我正在嘗試將自己的日志文件寫入 Databricks 中的 Python-Notebook 中的 Azure Datalake Gen 2。 我試圖通過使用 Python 日志記錄模塊來實現這一點。
不幸的是我無法讓它工作。 沒有出現錯誤,創建了文件夾,但沒有創建包含日志內容的文件。 即使文件存在,也不會寫入任何內容。
本地 python 腳本工作得很好,但我無法讓它在 Databricks 中工作。
這是我的代碼:
# mount
if not any(mount.mountPoint == '/mnt/log' for mount in dbutils.fs.mounts()):
dbutils.fs.mount(
source = "abfss://log@datalake.dfs.core.windows.net/",
mount_point = "/mnt/log",
extra_configs = configs)
# vars
folder_log = '/mnt/log/test/2019'
file_log = '201904.log'
# add folder if not existent
dbutils.fs.mkdirs(folder_log)
# setup logging
import logging
logging.basicConfig(
filename=folder_log+'/'+file_log,
format='%(asctime)s | %(name)s | %(levelname)s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S UTC (%z)',
level=logging.NOTSET
)
# test
logging.info('Hello World.')
安裝似乎沒問題。
使用 dbutils 添加和寫入文件效果很好:
dbutils.fs.put(folder_log+'/'+file_log, 'Hello World.')
像這樣寫入文件也可以正常工作:
f = open('/dbfs/mnt/log/test/2019/201904.log', 'w+')
f.write("This is line %d\r\n")
f.close()
還嘗試將“dbfs”添加到路徑
filename='/dbfs'+folder_log+'/'+file_log,
有任何想法嗎?
您可以使用 azure_storage_logging 處理程序:
import logging
from azure_storage_logging.handlers import BlobStorageRotatingFileHandler
log = logging.getLogger('service_logger')
azure_blob_handler = BlobStorageRotatingFileHandler(filename,
account_name,
account_key,
maxBytes,
container)
log.addHandler(azure_blob_handler)
讓我解釋一下使用 python 在 Azure 數據湖存儲上訪問或執行寫入操作的步驟
1) 在 Azure AD 中注冊一個應用程序
2)在數據湖中為您已注冊的應用程序授予權限
3) 請從 azure AD 為您注冊的應用程序獲取客戶端密碼。
4) 您需要編寫代碼將目錄掛載到 Azure 數據湖中,如下所示
dbutils.fs.mkdirs("/mnt/mountdatalake")
config = {"dfs.adls.oauth2.access.token.provider.type": "ClientCredential",
"dfs.adls.oauth2.client.id": "Registered_Client_Id_From_Azure_Portal",
"dfs.adls.oauth2.credential": "Cleint_Secret_Obtained_By_Azure_Portal",
"dfs.adls.oauth2.refresh.url":"https://login.microsoftonline.com/Your_Directory_ID/oauth2/token"}
dbutils.fs.amount(
source="adl://mydata.azuredatalakestore.net/mountdatabricks",
mount_point ="/mnt/mountdatalake",
extra_configs=configs)
使用應用程序客戶端憑據完成配置/安裝后,您就可以訪問目錄並記錄它了。
例如,下面我從 SQL Server 中提取了幾條記錄並將其存儲在 Azure 數據湖中
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.