Ansible default, and by far the most common pattern, is to let the task finish and register the output at the end. It has an async feature, however you need to query the job it makes in your playbook.
Rather, consider using init script features to background it. You tagged this Linux, such a thing with robust logging is pretty easy in a systemd unit.
vmstat outputs data regularly to stdout, and makes for a simple example. I present the silliest way to log vmstat output: /etc/systemd/system/dumbstat.service
[Unit]
Description=Dumb vmstat wrapper service example
Documentation=https://serverfault.com/questions/958952/ansible-task-write-to-local-log-file
[Service]
Type=oneshot
ExecStart=/usr/bin/vmstat 5 12
StandardOutput=journal
[Install]
WantedBy=multi-user.target
Type=oneshot
will wait in a starting state until the process exits. You may want a different type if you want more of an async fork and continue behavior.
Standard out is captured and available via the usual tools.
root@sf-958952:/var/log# systemctl status dumbstat
● dumbstat.service - Dumb vmstat wrapper service example
Loaded: loaded (/etc/systemd/system/dumbstat.service; disabled; vendor preset: enabled)
Active: activating (start) since Wed 2019-03-20 14:49:41 UTC; 7s ago
Docs: https://serverfault.com/questions/958952/ansible-task-write-to-local-log-file
Main PID: 3103 (vmstat)
Tasks: 1 (limit: 4401)
CGroup: /system.slice/dumbstat.service
└─3103 /usr/bin/vmstat -w 5 12
Mar 20 14:49:41 sf-958952 systemd[1]: Starting Dumb vmstat wrapper service example...
Mar 20 14:49:41 sf-958952 vmstat[3103]: procs -----------------------memory---------------------- ---swap-- -----io---- -system-- --------cpu--------
Mar 20 14:49:41 sf-958952 vmstat[3103]: r b swpd free buff cache si so bi bo in cs us sy id wa st
Mar 20 14:49:41 sf-958952 vmstat[3103]: 7 0 0 3104416 70260 417228 0 0 208 36 40 132 1 1 98 0 0
Mar 20 14:49:46 sf-958952 vmstat[3103]: 0 0 0 3107200 70260 417260 0 0 0 0 40 130 1 0 99 0 0
You also can filter the output by querying the systemd journal: journalctl _SYSTEMD_UNIT=dumbstat.service
By default the journal is forwarded to syslog, if you want a local file or to forward it somewhere.
Amusingly, system 240 and later can log direct to a file with StandardOutput=append:
but that's too new for CentOS 7 or Ubuntu 18.04.
All of this has little to do with Ansible. You can deploy such a unit with the template
module, and start it with the systemd
module.