Streamlit in Snowflake 에 대한 로깅 및 추적¶
예를 들어, Streamlit 앱 코드가 실행될 때 로그 메시지를 캡처하고 이벤트를 추적한 다음 SQL로 결과를 분석하여 오류를 분석할 수 있습니다. 자세한 내용은 로깅, 추적 및 메트릭 섹션을 참조하십시오.
이벤트 테이블 설정하기¶
Streamlit 앱 코드를 기록하고 추적하려면 이벤트 테이블을 생성하고, 이벤트 테이블을 계정과 연결하고, 기록 및 추적 이벤트 수준을 설정해야 합니다. 예:
-- Create an event table if it doesn't already exist
CREATE EVENT TABLE SAMPLEDATABASE.LOGGING_AND_TRACING.SAMPLE_EVENTS;
-- Associate the event table with the account
ALTER ACCOUNT SET EVENT_TABLE = SAMPLEDATABASE.LOGGING_AND_TRACING.SAMPLE_EVENTS;
-- Set the log level for the database containing your app
ALTER DATABASE STREAMLIT_TEST SET LOG_LEVEL = INFO;
-- Set the trace level for the database containing your app
ALTER DATABASE SAMPLEDATABASE SET TRACE_LEVEL = ON_EVENT;
자세한 내용은 이벤트 테이블 개요 섹션을 참조하십시오.
예: Streamlit 앱에서 로그 기록하기¶
import logging
import streamlit as st
logger = logging.getLogger("simple_logger")
# Write directly to the app
st.title("Simple Logging Example")
# Get the current credentials
session = st.connection('snowflake').session()
def get_log_messages_query() -> str:
"""
Get data from the `EVENT TABLE` where the logs were created by this app.
"""
return """
SELECT
TIMESTAMP,
RECORD:"severity_text"::VARCHAR AS SEVERITY,
RESOURCE_ATTRIBUTES:"db.user"::VARCHAR AS USER,
VALUE::VARCHAR AS VALUE
FROM
SAMPLE_EVENTS
WHERE
SCOPE:"name" = 'simple_logger'
ORDER BY
TIMESTAMP DESC;
"""
button = st.button("Log a message")
if button:
try:
logger.info("Logging an info message through Stremlit App.")
st.success('Logged a message')
except Exception as e:
logger.error("Logging an error message through Stremlit App: %s",e)
st.error('Logged an error')
sql = get_log_messages_query()
df = session.sql(sql).to_pandas()
with st.expander("**Show All Messages**"):
st.dataframe(df, use_container_width=True)
예: Streamlit 앱에서 추적 내보내기¶
참고
다음 예제에서는 snowflake-telemetry-python
패키지를 설치해야 합니다. 자세한 내용은 원격 분석 패키지에 대한 지원 추가하기 섹션을 참조하십시오.
import streamlit as st
import time
import random
from snowflake import telemetry
def sleep_function() -> int:
"""
Function that sleeps for a random period of time, between one and ten seconds.
"""
random_time = random.randint(1, 10)
time.sleep(random_time)
return random_time
def get_trace_messages_query() -> str:
"""
Get data from the `EVENT TABLE` where the logs were created by this app.
"""
return """
SELECT
TIMESTAMP,
RESOURCE_ATTRIBUTES :"db.user" :: VARCHAR AS USER,
RECORD_TYPE,
RECORD_ATTRIBUTES
FROM
SAMPLE_EVENTS
WHERE
RECORD :"name" :: VARCHAR = 'tracing_some_data'
OR RECORD_ATTRIBUTES :"loggin_demo.tracing" :: VARCHAR = 'begin_span'
ORDER BY
TIMESTAMP DESC;
"""
def trace_message() -> None:
"""
Add a new trace message into the event table.
"""
execution_time = sleep_function()
telemetry.set_span_attribute("loggin_demo.tracing", "begin_span")
telemetry.add_event(
"tracing_some_data",
{"function_name": "sleep_function", "execution_time": execution_time},
)
# Write directly to the app
st.title("Simple Tracing Example")
# Get the current credentials
session = st.connection('snowflake').session()
button = st.button("Add trace event")
if button:
with st.spinner("Executing function..."):
trace_message()
st.toast("Succesfully log a trace message!", icon="✅")
sql = get_trace_messages_query()
df = session.sql(sql).to_pandas()
with st.expander("**Show All Trace Messages**"):
st.dataframe(df, use_container_width=True)