How to see MySqlHook result in log

Viewed 8374

I am using MySqlHook to establish connection from airflow_db, and I am performing some query, but I need to see the result of the query somewhere ( let say log), how can I see?

Here is the sample code

t1 = MySqlOperator(
    task_id='basic_mysql',
    mysql_conn_id='airflow_db',
    sql="select * from xcom",
    dag=dag)
3 Answers

The MySQL operator currently (airflow 1.10.1 at time of writing) doesn't support returning anything in XCom, so the fix for you, for now, is to write a small operator yourself. You can do this directly in your DAG file:

from airflow.operators.python_operator import PythonOperator
from airflow.operators.mysql_operator import MySqlOperator
from airflow.hooks.mysql_hook import MySqlHook

class ReturningMySqlOperator(MySqlOperator):
    def execute(self, context):
        self.log.info('Executing: %s', self.sql)
        hook = MySqlHook(mysql_conn_id=self.mysql_conn_id,
                         schema=self.database)
        return hook.get_records(
            self.sql,
            parameters=self.parameters)

t1 = ReturningMySqlOperator(
    task_id='basic_mysql',
    mysql_conn_id='airflow_db',
    sql="select * from xcom",
    dag=dag)

def get_records(**kwargs):
    ti = kwargs['ti']
    xcom = ti.xcom_pull(task_ids='basic_mysql')
    string_to_print = 'Value in xcom is: {}'.format(xcom)
    # Get data in your logs
    logging.info(string_to_print)

t2 = PythonOperator(
    task_id='records',
    provide_context=True,
    python_callable=get_records,
    dag=dag)

t1 >> t2

AFAIK, MySqlOperator serves the purpose of running an UPDATE / DELETE etc. query; in other words queries which:

  • don't return any result
  • return result, but you are not bothered about it

In order to get hold of the actual result, you must exploit MySqlHook. Here's a small code-snippet (Python 3.6+) to get started (not tested, but just for hints)

from typing import List, Optional, Any
from airflow.hooks.mysql_hook import MySqlHook

# instantiate a MySqlHook
mysql_hook: MySqlHook = MySqlHook(mysql_conn_id="airflow_db")

# get records (this method comes from airflow.hooks.db_api_hook.DbApiHook)
records: List[List[Optional[Any]]] = mysql_hook.get_records(sql="select * from xcom")

# print records
print(records)

# alternatively, you can write records to task's logger
# note that here 'operator' = reference to your Operator
# operator.log.info("\n".join(records))

The output of print() / log.info() will appear in tasks's log on the UI

Generally with Airflow your query should be written such that results go into a temp table (maybe including the results_name_{{ds_nodash}}). You can then use the MySqlToSomethingElseOperator to move the temp table's results. Then clean up by dropping the table.

I don't see any reason that logging the results in Airflow logs would be sufficient work for a DAG to do.

Related