Repository: celery/celery

Issue:
empty line printed to stderr
<!--
Please fill this template entirely and do not erase parts of it.
We reserve the right to close without a response
bug reports which are incomplete.
-->
# Checklist
<!--
To check an item on the list replace [ ] with [x].
-->
- [x] I have verified that the issue exists against the `master` branch of Celery.
- [ ] This has already been asked to the [discussion group](https://groups.google.com/forum/#!forum/celery-users) first.
- [x] I have read the relevant section in the
  [contribution guide](http://docs.celeryproject.org/en/latest/contributing.html#other-bugs)
  on reporting bugs.
- [x] I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Bug+Report%22+-label%3A%22Category%3A+Documentation%22)
  for similar or identical bug reports.
- [y] I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22PR+Type%3A+Bugfix%22+-label%3A%22Category%3A+Documentation%22)
  for existing proposed fixes.
- [x] I have checked the [commit log](https://github.com/celery/celery/commits/master)
  to find out if the bug was already fixed in the master branch.
- [] I have included all related issues and possible duplicate issues
  in this issue (If there are none, check this box anyway).

## Mandatory Debugging Information

- [x] I have included the output of ``celery -A proj report`` in the issue.
    (if you are not able to do this, then at least specify the Celery
     version affected).
- [x] I have verified that the issue exists against the `master` branch of Celery.
- [x] I have included the contents of ``pip freeze`` in the issue.
- [x] I have included all the versions of all the external dependencies required
  to reproduce this bug.

## Optional Debugging Information
<!--
Try some of the below if you think they are relevant.
It will help us figure out the scope of the bug and how many users it affects.
-->
- [ ] I have tried reproducing the issue on more than one Python version
  and/or implementation.
- [ ] I have tried reproducing the issue on more than one message broker and/or
  result backend.
- [ ] I have tried reproducing the issue on more than one version of the message
  broker and/or result backend.
- [ ] I have tried reproducing the issue on more than one operating system.
- [ ] I have tried reproducing the issue on more than one workers pool.
- [ ] I have tried reproducing the issue with autoscaling, retries,
  ETA/Countdown & rate limits disabled.
- [x] I have tried reproducing the issue after downgrading
  and/or upgrading Celery and its dependencies.

## Related Issues and Possible Duplicates
<!--
Please make sure to search and mention any related issues
or possible duplicates to this issue as requested by the checklist above.

This may or may not include issues in other repositories that the Celery project
maintains or other repositories that are dependencies of Celery.

If you don't know how to mention issues, please refer to Github's documentation
on the subject: https://help.github.com/en/articles/autolinked-references-and-urls#issues-and-pull-requests
-->

#### Related Issues

- #6791
- #1997

#### Possible Duplicates

- None

## Environment & Settings
<!-- Include the contents of celery --version below -->
**Celery version**:
<!-- Include the output of celery -A proj report below -->
<details>
<summary><b><code>celery report</code> Output:</b></summary>
<p>

```
software -> celery:5.1.2 (sun-harmonics) kombu:5.1.0 py:3.8.5
            billiard:3.6.4.0 redis:3.5.3
platform -> system:Linux arch:64bit, ELF
            kernel version:5.8.0-59-generic imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:redis results:disabled

broker_url: 'redis://localhost:6379/0'
deprecated_settings: None
```

</p>
</details>

# Steps to Reproduce

## Required Dependencies
<!-- Please fill the required dependencies to reproduce this issue -->
* **Minimal Python Version**: N/A or Unknown
* **Minimal Celery Version**: N/A or Unknown
* **Minimal Kombu Version**: N/A or Unknown
* **Minimal Broker Version**: redis in docker 
* **Minimal Result Backend Version**: N/A or Unknown
* **Minimal OS and/or Kernel Version**: Ubuntu 20.04
* **Minimal Broker Client Version**: N/A or Unknown
* **Minimal Result Backend Client Version**: N/A or Unknown

### Python Packages
<!-- Please fill the contents of pip freeze below -->
<details>
<summary><b><code>pip freeze</code> Output:</b></summary>
<p>

```
amqp==5.0.6
billiard==3.6.4.0
celery @ file:///tmp/x/celery
click==7.1.2
click-didyoumean==0.0.3
click-plugins==1.1.1
click-repl==0.2.0
kombu==5.1.0
prompt-toolkit==3.0.19
pytz==2021.1
redis==3.5.3
six==1.16.0
vine==5.0.0
wcwidth==0.2.5

```

</p>
</details>

### Other Dependencies
<!--
Please provide system dependencies, configuration files
and other dependency information if applicable
-->
<details>
<p>
N/A
</p>
</details>

## Minimally Reproducible Test Case
<!--
Please provide a reproducible test case.
Refer to the Reporting Bugs section in our contribution guide.

We prefer submitting test cases in the form of a PR to our integration test suite.
If you can provide one, please mention the PR number below.
If not, please attach the most minimal code example required to reproduce the issue below.
If the test case is too large, please include a link to a gist or a repository below.
-->

<details>
<p>

```python
from celery import Celery

app = Celery('tasks', broker='redis://localhost:6379/0')


@app.task
def f():
    print('hello hello world')

if __name__ == '__main__':
    f.apply_async()
```

</p>
</details>

# Expected Behavior
only one line of output
<!-- Describe in detail what you expect to happen -->
```console
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery
                

[2021-06-30 19:28:02,606: WARNING/ForkPoolWorker-4] hello hello world
```
# Actual Behavior
prints an empty line
```console
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery
                

[2021-06-30 19:28:02,606: WARNING/ForkPoolWorker-4] hello hello world
[2021-06-30 19:28:02,607: WARNING/ForkPoolWorker-4] 
```
when printing from the task function, each output causes a newline to be printed to `stderr`. This was introduced in version `5.1.*` in #6791 by removing this line: https://github.com/celery/celery/pull/6791/commits/51f5b01df0434144521b23a35d16aebfee08c3ae#diff-116905b4c2ccc7e0172e26700ba1a0a0270b2fe1f830c47244dc1df07c805883L226

I think there are different options how to address this:
- just add the line back as it was -- but this would go against the initaly intention in #6791 of removing it to don't do any string manipulation in this function
- use something like `re.sub('\n|\r', '', data )` instead, to keep the whitespace or an endswith check or a more complex regex?
- address this somewhere else, so no newline characters are passed to `.write()` (I would need a hint where to do this though)

I am happy to send a PR to fix this if needed. 


Discussion:
Hey @theendlessriver13 :wave:,
Thank you for opening an issue. We will get back to you as soon as we can.
Also, check out our [Open Collective](https://opencollective.com/celery) and consider backing us - every little helps!

We also offer priority support for our sponsors.
If you require immediate assistance please consider sponsoring us.


Resolving patch:
diff --git a/celery/utils/log.py b/celery/utils/log.py
--- a/celery/utils/log.py
+++ b/celery/utils/log.py
@@ -223,6 +223,7 @@ def write(self, data):
         if getattr(self._thread, 'recurse_protection', False):
             # Logger is logging back to this file, so stop recursing.
             return 0
+        data = data.rstrip('\n')
         if data and not self.closed:
             self._thread.recurse_protection = True
             try:


Test patch:
diff --git a/t/unit/app/test_log.py b/t/unit/app/test_log.py
--- a/t/unit/app/test_log.py
+++ b/t/unit/app/test_log.py
@@ -268,8 +268,10 @@ def test_logging_proxy(self):
             p.write('foo')
             assert 'foo' not in sio.getvalue()
             p.closed = False
+            p.write('\n')
+            assert sio.getvalue() == ''
             write_res = p.write('foo ')
-            assert 'foo ' in sio.getvalue()
+            assert sio.getvalue() == 'foo \n'
             assert write_res == 4
             lines = ['baz', 'xuzzy']
             p.writelines(lines)